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.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 25, 2024 (edit).