StreamWriter ExamplesUse StreamWriter from System.IO to write text files. Place StreamWriter in using statements.
This page was last reviewed on May 9, 2023.
StreamWriter. This helpful C# class writes text data and files. It enables easy and efficient text output. It is one of the first choices for file output in C#.
Using statements. StreamWriter is best placed in a using-statement. This ensures it is removed from memory when no longer needed. The syntax is easy to use once it is familiar.
First example. We first declare and initialize a new StreamWriter instance in a using construct. Please note how the System.IO namespace is included at the top of the file.
Important The "using" keyword means different things in different places. Near StreamWriter, it controls low-level resource usage.
Here A new StreamWriter is initialized with the file name "important.txt". Three writes are done using StreamWriter.
Info The Write method does not append a newline. The WriteLine methods append a newline "\r\n" at each call.
using System.IO; using (StreamWriter writer = new StreamWriter("important.txt")) { writer.Write("Word "); writer.WriteLine("word 2"); writer.WriteLine("Line"); }
(Text is in "important.txt" file.) Word word 2 Line
Append text. It is easy to append text to a file with StreamWriter. The file is not erased, but just reopened and new text is added to the end. We also see how you can specify a full path.
Start A new StreamWriter is initialized and it opens "C:\log.txt" for appending. The second argument (true) specifies an append operation.
Next The first line is appended to the file. If it is empty, the file begins with that string.
Then The second using construct reopens the "C:\log.txt" file and appends another string to it.
Note If for some reason the file was deleted, the line will be added just the same.
using System.IO; // Write single line to new file. using (StreamWriter writer = new StreamWriter("C:\\log.txt", true)) { writer.WriteLine("Important data line 1"); } // Append line to the file. using (StreamWriter writer = new StreamWriter("C:\\log.txt", true)) { writer.WriteLine("Line 2"); }
(File "log.txt" contains these lines.) Important data line 1 Line 2
Loop. Often we need to write out an array or List of strings. A good solution is to put the loop inside the using statement. This avoids creating more than one file handle in Windows.
Tip We use var, which makes the syntax shorter but equivalent in functionality. The file "loop.txt" is opened only once for writing.
Detail The format string can be easily used with Write. You have to specify a substitution marker {0} in the first parameter.
using System.IO; // Use var type which is shorter. using (var writer = new StreamWriter("loop.txt")) { // Loop through ten numbers. for (int i = 0; i < 10; i++) { // Write format string to file. writer.Write("{0:0.0} ", i); } }
(These numbers are in the file "loop.txt".) 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
String interpolation. This syntax can be used to directly insert variables into a string before it is written with Write or WriteLine. We use the "$" char before the string.
Note String interpolation is about as fast as the older format syntax—it is a good alternative.
String Interpolation
using System.IO; using (StreamWriter writer = new StreamWriter("C:\\programs\\file.txt")) { string animal = "cat"; int size = 12; // Use string interpolation syntax to make code clearer. writer.WriteLine($"The {animal} is {size} pounds."); }
The cat is 12 pounds.
Encodings. StreamWriter accepts a parameter that specifies encoding. This is useful in some globalization contexts. Many projects will not need specialized encodings.
Using. The using statements in the examples open and prepare the files. At the end of the statements they close and dispose of the resources.
Tip If your program does lots of writes, it will manage system resources correctly if you use using.
Early returns. With using, if your program returns in the middle of a using statement, the resources will still be disposed. This statement is implemented with a finally statement.
Tip Finally statements always run—they are stubborn about that. They will not run only in an Environment.Exit call or a crash.
Dispose, Close. You can call Dispose and Close on your StreamWriter. You only should do this if you are not using the "using" keyword. This is a more error-prone style.
A summary. With the using-statement and StreamWriter, we wrote text files. StreamWriter is an excellent class—it is useful for many C# developers.
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 May 9, 2023 (simplify).
© 2007-2023 Sam Allen.