FileStream Example, File.Create
This page was last reviewed on Jan 25, 2024.
Dot Net Perls
FileStream. In .NET we often access files through streams. We can place one stream on top of another (usually with "using" statements).
This is powerful. 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.
Example. 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.
Info We pass the 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"); } }
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.
Here We open the FileStream using the return value of File.OpenRead. This works like the FileStream constructor with certain parameters.
Result The length of the file is written to the 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); } } }
Some notes. 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, methods. Streams 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.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 25, 2024 (edit).
© 2007-2024 Sam Allen.