C# FileStream Example, File.Create

Use FileStream and File.Create to create a file. Another object like StreamWriter can be used with FileStream.

dot net perls

FileStream. In the .NET Framework we often access files through streams. We can place one stream on top of another (usually with "using" statements).File

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.

An 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.File.Open
StreamWriter: We pass the FileStream object we get from File.Create to a StreamWriter. We then use WriteLine to write to the file.
C# program that uses FileStream, File.Create 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"); } } Output DONE Contents of example1.txt: Example 1 written

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.
And: Often the FileStream serves as a "base" to other streams we might use. The example above shows this.

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.StreamMemoryStreamBaseStreamFileStream Length

A brief 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.


© 2007-2020 sam allen. send bug reports to info@dotnetperls.com.