Tuesday, December 21, 2010

C# Read/Write From File

A lot of the more advanced programs that you will write will require reading from and writing to the hard drive.  This basically means saving and loading files for your program.

Most operations involving your hard drive will need the namespace System.IO, so add the following statement to the top of your class:
using System.IO;

To read from your hard drive, using the following line:
string fileText = File.ReadAllText("file_name");

You should replace "file_name" with whatever file you want to read.  Remember that you have to include the file extension.  The contents of "file_name" will be put into a string called fileText (or whatever you want to call this variable).

To write to the hard drive, use the following line:
File.WriteAllText("file_name", "text");

Again, replace "file_name" with the name of the file you want to save it as, and you still have to include the extension if the file is supposed to have one.  "Text" is whatever you want to put into the file.  Obviously, you can have a string variable instead of just some text in quotes.

I think that those two methods are the most useful in the System.IO namespace, but if you're still interested in all sorts of the other cool things in the System.IO namespace, see this site:
http://msdn.microsoft.com/en-us/library/system.io.aspx

No comments:

Post a Comment