C# Input, Output, Other File Operations, and Persisting Data
Welcome to the 9th tutorial in the "C# for the Completely Uninitiated" series.
- Creating Files Programmatically
- Reading Files
- Checking For File Existence
- Moving a File to Another Location
Source code used in this tutorial:
Creating Files Programmatically
The first thing you need to know about file operations in C#, such aswriting to a file, reading data from a file, etc., is that you mustplace a using reference to System.IO at the top of your source code (just beneath using System; is a good place):

As you can see in line #2, we include areference to the System.IO namespace, which contains classes forworking with input and output.
We can add a single line of code (line #8) inside our Main() method, to create a text file in our application's directory:

Run the program, then navigate to theapplication's executable directory under your projects folder, toconfirm that "myfile.txt" has indeed been created:

Notice that the file shows 0 Kb, which is what we would expect. We merely created a text file. We did not write any data to it. The file can have any extension you want, not just .txt,or no extension at all, but consider that here we created a text file(see line #8 in the source code) and therefore the file is writtenusing ASCII characters. A binary file is created the same way, justthat instead of using File.CreateText() you use File.Create().At first you won't notice any difference between the text file and thebinary file but it matters a lot because it is stored differently. Youuse the text file for storing text and the binary file for storingnon-text data.
Let's run the program again, but before we doso, let's update the source code so that it will actually cause thecreated text file to contain a line of text. We'll use something calleda StreamWriter object. This object is instantiated from a class in the System.IO namespace that is used for writing data to files.

Now, run the program, then navigate to theapplication directory and examine the "myfile.txt" file. You'll seethat it is no longer an empty file. It should now show 1 Kb:

If you double-click the file and examine its contents, you'll see something like the following:

It should be apparent what is going on here. With the help of a StreamWriterobject, we are writing a string to the text file. You could replace thestring I used, in line # 10, with any string of your choice, such as "Epluribus unum" or "Mi casa su casa". Use the program we just wrote towrite the following line of text to the file: The name is Bond… James Bond. Then exit the program and prepare to write a different program.
Reading a Text File
We can use C# to read either text or binary files. For the purpose ofthis introductory level tutorial, we'll only be focusing on text files.In a later tutorial, in another series altogether, I'll address writingand reading binary files.
What we're going to do now is write a programthat will open the "myfile.txt" text file and read the line of textthat it contains. Delete the current code in the project source codewindow, and paste this source code. Run this new program, and you should see the following output:

It is also possible to read text from a file one character at a time. Sometimes this can be useful, although in our previous example, the ReadLine() method of the StreamReaderclass was more appropriate. However, to see how to do it by reading itone character at a time, examine the following source code listing:

Note that we are using an integer variable to hold the value returned by each call to sr.Read();this is due to the fact that the method returns an integer value thatis the ASCII value of the character just read from the file. We thenhave to convert that ASCII value to a character (as you can see in line# 16). Probably the most complex line of code in the source codelisting shown above is line # 14. If the StreamReader object attemptsto read in a character from the file and is unsuccessful due to the endof the file having been reached, a value of negative one is returned.
lass="sm
allblack">
Checking For File Existence
If you attempt to open a file that isn't there, an exception will bethrown. Exceptions are ugly. They make users feel that your software isbuggy (not without some justification). You should check to ensure thata particular file exists on disk before attempting to open it. The System.IO namespace provides the FileExists() method, which will return true if the file path you pass into the method as a parameter is valid, or falseif it isn't. If your program creates a file and does not specify a pathfor it, it will, by default, be created in the directory in which theexecutable that is attempting to create the file is located. In C#projects, this will be the Debug or Release directory of the particularproject you're working on. I used this default directory in my examplesabove, where I demonstrated writing to a file, and then reading fromthat file.
You have to be careful about making assumptions when programming. You should not automatically assume that you're current directoryis the application executable's directory, because code can change theworking directory. To demonstrate this, I've added a single line ofcode (line #8 in the image below) to oneof the example programs we did earlier. The only thing line #8 does,below, is set the current directory to somewhere other than theapplication directory (which is where our file was created). You cansee the nasty error that is caused when you assume that you're in thecorrect directory when attempting to open a file.

You may not clearly understand the ratherunusual looking code in the example program for which I provide a linkabove. For example,
if ((fi.Attributes & FileAttributes.ReadOnly) != 0){
// do this…
}
To break that down for you, simply know that whenever you see something in C# that looks like this:
if((BlahBlahThis & BlahBlahThat) != 0)
…what's being said is "if it's true that thestuff inside the nested parentheses is the case, then do thefollowing…" You can think of !=0 as "not not the case", in other words is the case.
There are other attributes that we didn't usein the code but you can easily figure them out thanks to IntelliSense,if you're using the Visual C# 2005 or the Visual C# 2005 Expressedition IDE.
Moving a File to Another Location
There is a method of the File object named Copy(). You can use it to copy a file from one location to another. Thissource code listing shows an example of copying a file from theapplication directory to your desktop directory. Copying a file doesn'teliminate the original file. If you want to move a file, i.e.,make it disappear from its current location and reappear in anotherdirectory, then you first copy it to the desired destination, thenfollow up by deleting it from the source directory. So, in the aboveexample, you could add the following line immediately after theinvocation of the File object's Copy() method, to change the program's function from copying to moving the file:
File.Delete("myfile.txt"); //deletes original file from the application's executable directory
In this tutorial, I've addressed only the most basic of input and output using the System.IOnamespace. With a reference to this namespace, we've been able to useinstances of the streamreader and streamwriter classes to either openan existing text file and read in its contents, or else write a newtext file to disk. You've also been shown how to read the data from atext file one character at a time, or, alternatively, one entire lineat a time. I've explained the importance of checking for fileexistence, and couching your read/write operations inside a try-catchblock. Although quite basic, you now have the skills to develop asimple computer roleplaying game. We'll be working on that throughoutthe next series, "C# for the Somewhat Initiated",a series that introduces WinForms programming, and some programmingtips and tricks that are bit more advanced than those covered in thisseries' nine tutorials.
Well, I hope that you've benefited, at least a little, from this tutorial and, indeed, all of the tutorials in the "C# for the Completely Uninitiated" series. As ever, I welcome any feedback you may wish to impart.












No comments yet... Be the first to leave a reply!