FileStream
In .NET we often access files through streams. We can place one stream on top of another (usually with "using" statements).
For the FileStream
, we often need to use another stream (like StreamWriter
) on top of it. We can do many things with a file using a FileStream
.
Here we get a FileStream
using the File.Create
method. Other methods, like File.Open
or File.OpenText
can be used to get a FileStream
.
FileStream
object we get from File.Create
to a StreamWriter
. We then use WriteLine
to write to the file.using System; using System.IO; class Program { static void Main() { // Use FileStream with File.Create. // ... Pass FileStream to a StreamWriter and write data to it. using (FileStream fileStream = File.Create(@"C:\programs\example1.txt")) using (StreamWriter writer = new StreamWriter(fileStream)) { writer.WriteLine("Example 1 written"); } Console.WriteLine("DONE"); } }DONE
Length
FileStream
has a Length
property that will return the length of a file in bytes. This is bytes, not chars, meaning some Unicode strings will have different lengths.
FileStream
using the return value of File.OpenRead
. This works like the FileStream
constructor with certain parameters.Console
. The size of a 35-byte
file was correctly written by the program.using System; using System.IO; class Program { static void Main() { // Open existing text file with File.OpenRead using (FileStream fileStream = File.OpenRead("TextFile1.txt")) { // Use Length property to get number of bytes long length = fileStream.Length; // Write length to console Console.WriteLine("Length: {0}", length); } } }
It is important to understand how streams can be used together to develop complex (and custom) file handling routines in C#. Many stream types are available.
Stream
types, methodsStreams can act on a physical file (as with FileStream
) or a logical piece of memory (as with MemoryStream
). We can act upon these streams in a similar way.
Understanding the dynamics of streams is important. For more complex tasks, a FileStream
is often useful as many streams are combined in methods, one acting upon another.