Input/Output 9: FileStream
The Basics
The FileStream class represents a stream that wraps a file. You use FileStream for reading and writing bytes of a file. The FileStream class uses buffering to improve performance. The easiest way to construct a FileStream object is to use one of its constructors, which accepts a file path and a value from the FileMode enumeration as arguments. For instance, the following code creates a file called newFile.txt and writes two bytes into it. If the file already exists, the file will be overwritten:
FileStream fs = new FileStream("C:/newFile.txt",
FileMode.Create);
Byte[] bytes = new Byte[2];
bytes[0] = 65;
bytes[1] = 66;
fs.Write(bytes, 0, 2);
fs.Close();
Some methods return a FileStream object without requiring that you create it with one of its constructors. For example, the following code uses the File class' Create method to create a file called newFile.txt, returns a FileStream object, and then writes two bytes to the file:
FileStream fs = File.Create("C:/newFile2.txt");
Byte[] bytes = new Byte[2];
bytes[0] = 65;
bytes[1] = 66;
fs.Write(bytes, 0, 2);
fs.Close();
If you want to append to a file instead of creating a new one, you must use the FileStream constructor that accepts a FileMode and a FileAccess value, and you must specify FileAccess. Write for the file access type, as shown in the following code:
FileStream fs = new FileStream("C:/newFile.txt",
FileMode.Append, FileAccess.Write);
To read from a file, you can use FileMode. Open as the file mode argument in one of the FileStream class' constructors. The following code, for instance, reads two bytes from the newFile.txt file:
FileStream fs = new FileStream("C:/newFile.txt",
FileMode.Open);
Byte[] bytes = new Byte[2];
int i = fs.Read(bytes, 0, 2);
fs.Close ();
Source: http://www.ondotnet.com/pub/a/dotnet/2002/08/05/io.html?page=5
Article comments
Feel free to comment this article using a facebook profile.
I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.