Simple File IO in .NET
It is fairly easy to perform read/write options to files in .NET. There are three objects you
might need:
-
FileStream
-
StreamReader, or
-
StreamWriter
There are 15 ways to use a FileStream object, but we only care about one. When we create a
FileStream, we will give it a file name, a type file mode, and a type of file access. To read a file,
we will specify FileMode.Open, to write a file we will specify FileMode.Create. As for file access,
we will specify FileAccess.Read or FileAccess.Write, depending on whether we want to read or write!
Sample Code:
using System.IO;
using (FileStream fs = new FileStream(FILE_PATH,
FileMode.Open, FileAccess.Read)) {
using (StreamReader sr = new StreamReader(fs)) {
while (sr.Peek() != -1) {
string aLine = sr.ReadLine();
}
}
}
Notes:
-
FILE_PATH is assumed to be a string constant containing the path to your file
-
I utilized the 'using' keyword to ensure that my objects are disposed after I'm don
-
Note that .NET unfortunately utilizes the keyword 'using' in two separate contexts,
one meaning to import a library, the other meaning to dispose of a variable once
it has gone out of scope.
-
StreamReader.Peek() looks at the next entry in the file without consuming it, thus
it is a safe way to detect end of file conditions.
Writing to a file utilizes almost exactly the same techniques, but with different FileMode and FileAccess.
Take a look at this sample:
using System.IO;
using (FileStream fs = new FileStream(FILE_PATH,
FileMode.Create, FileAccess.Write)) {
using (StreamWriter sw = new StreamWriter(fs)) {
sw.WriteLine("This is my file contents");
}
}