9 Replies - 12442 Views - Last Post: 27 November 2010 - 07:11 PM Rate Topic: -----

#1 Guest_Jonez*


Reputation:

Save to file in C#

Posted 26 November 2010 - 03:34 PM

In my Main I create a bunch of arrays with results of stuff, now I need to create a file and save it all to it. Can anyone point me in the right direction to go about doing this, like a website that could explain. I am a beginner and I know how to make a method to create a file I just don't know how you would tell the program to take all those results, create a file and put those results in it.

Thanks,
Jonez
Is This A Good Question/Topic? 0

Replies To: Save to file in C#

#2 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 992
  • View blog
  • Posts: 972
  • Joined: 30-September 10

Re: Save to file in C#

Posted 26 November 2010 - 04:05 PM

Hello there,

The easiest way to write to a file is using the StreamWriter class. Here is a link to the MSDN documentation on the class: http://msdn.microsof.../3ssew6tk.aspx.

Here is a little snippet to get you started:


using(StreamWriter writer = new StreamWriter(@"FilePathGoesHere")){

writer.WriteLine("Hello, World!");

}




That would simply write "Hello, World!" to the file pointed to by the file path (presumably it would be a .txt file in this case). If the file exists, then it will open the file and wrtie to it. If it doesn't exist, it will create the file and write to it! The 'using' statement is just a means of ensuring the resources occupied by the StreamWriter object are released and disposed of. It means that you do not have to explicitly close the stream yourself using:

writer.Close() //in the context of the above example


If you want to open an existing file that already has text in, and you want to add text onto the end of the file, use this line in place of the corresponding line above:

using(StreamWriter writer = new StreamWriter(@"FilePathGoesHere",true)){ }



I have just added an extra arguement. That just says, 'I want to append text onto the end of this file, rather than overwrite the existing file'.

In order to write the contents of the arrays to the file, presumably you would loop through the arrays (perhaps using a foreach loop; depending on what you need), and write each element to the file using calls to the StreamWriter class' WriteLine(), Write() etc.

Tutorials
Here is a very specific tutorial that deals with the StreamWriter class. It even talks about using loops in conjuction with the class, which is what you will need I think:
http://dotnetperls.com/streamwriter

Refer to this tutorial for more information on the foreach loop :):
http://www.dreaminco...er__all__st__90

Here is part 1 of a 3 part (I think) tutorial on IO and generally working with files in c#. This will definately clear up any difficulties you may be having.
http://www.dreaminco...in-c%23-part-i/

This post has been edited by CodingSup3rnatur@l-360: 26 November 2010 - 04:44 PM

Was This Post Helpful? 2
  • +
  • -

#3 Guest_Guest*


Reputation:

Re: Save to file in C#

Posted 26 November 2010 - 07:14 PM

I was going to write a method to create the file because I will have to run my program several times, and with each iteration an incremented number gets put at the end of the file name. So how would you incorporate that method within the the call to put all the information to that file, that is where I am getting sooooooo confused.

Thanks,
Jonez
Was This Post Helpful? 0

#4 CodderMan  Icon User is offline

  • New D.I.C Head

Reputation: 10
  • View blog
  • Posts: 48
  • Joined: 18-November 10

Re: Save to file in C#

Posted 27 November 2010 - 07:08 AM

Well you can do this yourself I think. if you really can't only then read this.

Quote

If you want to open an existing file that already has text in, and you want to add text onto the end of the file, use this line in place of the corresponding line above:
using(StreamWriter writer = new StreamWriter(@"FilePathGoesHere",true)){ }


Or you could use the File.AppendText(@"Path") method.

As for the method you just write the snippet that CodingSup3rnatur@l-360 has clearly pointed out to you.

Or like:
 
void WriteToFile(object sender, EventArgs e)
        {
            StreamWriter myStreamWriter = new StreamWriter(@"Path");
            myStreamWriter.WriteLine(thingsToWrite);

            //Or

            TextWriter myTextWriter = new StreamWriter(@"Path");
            myTextWriter.WriteLine(thingsToWrite);
        }



But by using this you have add the using System.IO; statement.
Was This Post Helpful? 0
  • +
  • -

#5 Guest_Linez*


Reputation:

Re: Save to file in C#

Posted 27 November 2010 - 01:11 PM

I've made a method but I don't understand why it doesn't work. It will create a new file name with each iteration of the program but it won't make the file. Also, I don't understand how you would call to it: using(StreamWriter writer = new StreamWriter(@"FilePathGoesHere")) if the path name will change every time so I don't really have a string to pass into it but instead the result of a method.

public static void createItFile(int iteration)
        {
                FileStream outfilestream = null;
                StreamWriter outstreamwriter = null;
                int flag = 0;
                string fileName = null;

                for (int i = 1; i <= iteration; i++)
                {

                    fileName = ("C\\:MyFile" + i + ".dat");

                }

                
                    try
                    {
                        outfilestream = new FileStream(fileName, FileMode.Create);
                        outstreamwriter = new StreamWriter(outfilestream);
                    }

                    catch 
                    {
                        Console.WriteLine("Does not exist");
                        flag = 1;
                    }

                    if (flag == 0) 
                    {
                        Console.WriteLine("Data has been written to the file: " + fileName);

                        outstreamwriter.Close();
                        outfilestream.Close();
                    }
                    Console.WriteLine("File name created: " + fileName);
                
                return;
        }


MOD EDIT: When posting code...USE CODE TAGS!!!

:code:

This post has been edited by JackOfAllTrades: 27 November 2010 - 01:35 PM

Was This Post Helpful? 0

#6 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6107
  • View blog
  • Posts: 23,659
  • Joined: 23-August 08

Re: Save to file in C#

Posted 27 November 2010 - 01:37 PM

Ummm....because you're not actually writing anything to the file? Just opening isn't enough you know...you need to actually WRITE SOMETHING.
Was This Post Helpful? 0
  • +
  • -

#7 Guest_Linez*


Reputation:

Re: Save to file in C#

Posted 27 November 2010 - 02:14 PM

I have since changed a few things but it still gets caught in the Catch and doesn't create a file.
public static void createItFile(int iteration)
02
        {
03
                FileStream outfilestream = null;
04
                StreamWriter outstreamwriter = null;
05
                int flag = 0;
06
                string fileName = null;
07
 
08
                for (int i = 1; i <= iteration; i++)
09
                {
10
 
11
                    fileName = ("C\\:MyFile" + i + ".dat");
12
 
13
                }
14
 
15
                 
16
                    try
17
                    {
18
                        outfilestream = new FileStream(fileName, FileMode.Create);
19
                        outstreamwriter = new StreamWriter(File.Create(fileName));
20
                    }
21
 
22
                    catch
23
                    {
24
                        Console.WriteLine("Does not exist");
25
                        flag = 1;
26
                    }
27
 
28
                    if (flag == 0)
29
                    {
30                     outstreamwriter.WriteLine("Writing text to file");
                        Console.WriteLine("Data has been written to the file: " + fileName);
31
 
32
                        outstreamwriter.Close();
33
                        outfilestream.Close();
34
                    }
35
                    Console.WriteLine("File name created: " + fileName);
36
                 
37
                return;
38
        }


Was This Post Helpful? 0

#8 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 992
  • View blog
  • Posts: 972
  • Joined: 30-September 10

Re: Save to file in C#

Posted 27 November 2010 - 02:37 PM

Hello again,

For one thing, you may want to look your file paths. In particular:

Quote

"C\\:"


Is that colon (':') in the right place?

Also, I don't think you need the 'outfilestream' variable. You don't use it. Your creating a FileStream object with the call to File.Create();.

Also, with your code, you will end up with only one file. You are looping through and creating the file paths, but you are storing them all in the same string variable. Therefore, at the end of the loop, the string variable will contain only one file path, and as you are calling File.Create() once only, only one file will be created. You need to incorporate the call to File.Create() into the loop so that multiple files are created. Either that, or create an array (or generic list) of file paths and loop through them, passing each one to File.Create()...

This post has been edited by CodingSup3rnatur@l-360: 27 November 2010 - 03:48 PM

Was This Post Helpful? 0
  • +
  • -

#9 Guest_Linez*


Reputation:

Re: Save to file in C#

Posted 27 November 2010 - 06:05 PM

Oh geez, I can't believe I missed that one. I've been staring at this for about a week and it must have dazed over my eyes. Thanks for catching that. I am still confused though how to get all my results into the file that I have now created. My thinking is that my program will be
createFile(iteration);

                    using (StreamWriter writer = new StreamWriter(File.OpenWrite(createFile(iteration)))
                    {
                        writer.WriteLine("First array:");

                         .....other code stuff
                        for (int i = 0; i < myArray.Length; i++)
                        {
                            writer.WriteLine(myArray[i]);
                        }
                      }


but I get an error. It doesn't like the (File.OpenWrite(createFile(iteration))) part and I don't understand why this doesn't work.
Was This Post Helpful? 0

#10 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5675
  • View blog
  • Posts: 12,192
  • Joined: 02-June 10

Re: Save to file in C#

Posted 27 November 2010 - 07:11 PM

I am going to guess that you are trying to teach yourself C# without much guidance, a decent book or without knowing where to look. Sometimes just knowing where to look can make all the difference. Google is your friend.
Search with either "C#" or "MSDN" as the first word: "MSDN Picturebox", "C# Custom Events", "MSDN timer" etc.

But honestly, just typing away and seeing what pops up in Intellisense is going to make your self-education take 20 years. You can learn by trying to reverse engineer the language through banging on the keyboard - or you can learn by doing the tutorials and following a good "How to learn C#" book.

May I suggest picking up a basic C# introductory book? It's not that people here don't want to be helpful, but there is a certain amount of basic learning work that one should really take upon themselves before asking for help. There are so many great "How do I build my first application" tutorials on the web... There are dozens of "Learn C# in 21 days", "My first C# program" books at your local book seller or even public library... Asking a forum, any forum, to hand-hold you through it is just redundant. In many ways it disrespects the people who have invested dozens of hours in the on-line tutorials and those that spent thousands of hours in authoring books.

Build a Program Now! in Visual C# by Microsoft Press, ISBN 0-7356-2542-5
is a terrific book that has you build a Windows Forms application, a WPF app, a database application, your own web browser.

C# Cookbooks
Are a great place to get good code, broken down by need, written by coding professionals. You can use the code as-is, but take the time to actually study it. These professionals write in a certain style for a reason developed by years of experience and heartache.

Microsoft Visual Studio Tip, 251 ways to improve your productivity, Microsoft press, ISBN 0-7356-2640-5
Has many, many great, real-world tips that I use all the time.

The tutorials below walk through making an application including inheritance, custom events and custom controls.
Quick and easy custom events
Bulding an application - Part 1
Building an application - Part 2
Debugging tutorial
Working with environmental variables

Writing a text file is always one of the first things people want to do, in order to store data like high-scores, preferences and so on
Writing a text file tutorial.

These are just good every-day references to put in your bookmarks.
MSDN C# Developers Center with tutorials
Welcome to Visual Studio

Have you seen the MSDN Code Samples? They spent a lot of time creating samples and demos. It seems a shame to not use them.

  • Anonymous Delegates: Demonstrates the use of unnamed delegates to reduce application complexity.
  • Arrays: Shows how to use arrays.
  • Attributes: Shows how to create custom attribute classes, use them in code, and query them through reflection.
  • Collection Classes: Shows how to make non-generic collection classes that can be used with the foreach statement.
  • COM Interop Part I: Shows how to use C# to interoperate with COM objects.
  • COM Interop Part II: Shows how to a use a C# server together with a C++ COM client.
  • Commandline: Demonstrates simple command-line processing and array indexing.
  • Condiational Methods: Demonstrates conditional methods, which provide a powerful mechanism by which calls to methods can be included or omitted depending on whether a symbol is defined.
  • Delegates: Shows how delegates are declared, mapped to static and instance methods, and combined into multicast delegates.
  • Events: Shows how to declare, invoke, and configure events in C#.
  • Explicit Interface: Demonstrates how to explicitly implement interface members and how to access those members from interface instances.
  • Generics: Shows how to make generic collection classes that can be used with the foreach statement.
  • Hello World: A Hello World application.
  • Indexers Part I: Shows how C# classes can declare indexers to provide array-like access to objects.
  • Indexers Part II: Shows how to implement a class that uses indexed properties. Indexed properties enable you to use a class that represents an array-like collection.
  • Libraries: Shows how to use compiler options to create a DLL from multiple source files; also, how to use the library in other programs
  • Named and Optional (C# 4.0): Demonstrates Named and Optional parameters, an alternative to method overloads
  • Nullable: Demonstrates value types, such as double and bool, that can be set to null
  • Office Sample (C# 4.0): Demonstrates how Dynamic and COM Interop make it easy to call Microsoft Office in C# 4.0
  • OLEDB: Demonstrates how to use a Microsoft Access database from C# by creating a dataset and adding tables to it.
  • Operator Overloading: Shows how user-defined classes can overload operators
  • Partial Types: Demonstrates how classes and structures can be defined in multiple C# source-code files
  • PInvoke: Shows how to call exported DLL functions from C#
  • Properties: Shows how properties are declared and used; also demonstrates abstract properties
  • Python Sample (C# 4.0): Learn how to call a Python script by using the Dynamic feature in C# 4.0
  • Security: Discusses .NET Framework security and shows how to modify security permissions in C# by using permission classes and permission attributes
  • Simple Variance (C# 4.0): See how Covariance and Contravariance are supported in generic interfaces and delegates
  • Structs: Shows how to use structs in C#.
  • Threading: Demonstrates various thread activities such as creating and executing a thread, synchronizing threads, interacting between threads, and using a thread pool
  • Unsafe: Shows how to use unmanaged code (code that uses pointers) in C#
  • User Conversions: Shows how to define conversions to and from user-defined types
  • Versioning: Demonstrates versioning in C# by using the override and new keywords
  • XML Documents: Shows how to document code by using XML
  • Yield: Demonstrates how to use the yield keyword to filter items in a collection

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1