StreamWriter | C# Examples

StreamWriter is a class in C# that provides a convenient way to write text to a file. It is located in the System.IO namespace. The StreamWriter class creates a new file or overwrites an existing file with the specified encoding and writes text to it.

To use StreamWriter, you first need to create an instance of the class by passing the path of the file that you want to write to as a parameter to the constructor. You can then call the various methods of the StreamWriter class to write text to the file.

Some of the common methods of the StreamWriter class include Write(), WriteLine(), and Flush(). Write() writes a string to the file, WriteLine() writes a string followed by a line terminator to the file, and Flush() flushes the buffer to ensure that all the data is written to the file.

You should always close the StreamWriter object after you are done writing to the file to ensure that the file is properly closed and any buffered data is written to the file.

Following are some of the most commonly used methods of the StreamWriter class:

Write(string):

This method writes a string to the file without adding a line terminator.

using System; using System.IO; public class MyProgram { public static void Main(string[] args) { StreamWriter writer = new StreamWriter("file.txt"); writer.Write("Python, Examples!"); writer.Close(); } }

This code creates a StreamWriter object to write to a file named "file.txt", writes the string "Python, Examples!" to the file, and then closes the StreamWriter object.

WriteLine(string):

This method writes a string to the file and adds a line terminator at the end.

StreamWriter writer = new StreamWriter("file.txt"); writer.WriteLine("Python,"); writer.WriteLine("Examples!"); writer.Close();

This code creates a StreamWriter object to write to a file named "file.txt", writes the string "Python," followed by a line terminator, writes the string "Examples!" followed by another line terminator, and then closes the StreamWriter object.

Write(char):

This method writes a single character to the file.

using System.IO; StreamWriter writer = new StreamWriter("file.txt"); writer.Write('P'); writer.Write('y'); writer.Write('t'); writer.Write('h'); writer.Write('o'); writer.Write('n'); writer.Close();

This code creates a StreamWriter object to write to a file named "file.txt", writes the characters 'P', 'y', 't', 'h', 'o' and 'n' to the file, and then closes the StreamWriter object.

Write(int):

This method writes an integer to the file.

using System.IO; StreamWriter writer = new StreamWriter("file.txt"); writer.Write(56); writer.Close();

This code creates a StreamWriter object to write to a file named "file.txt", writes the integer 56 to the file, and then closes the StreamWriter object.

Flush():

This method flushes the buffer to the file, ensuring that all data is written to the file.

using System.IO; StreamWriter writer = new StreamWriter("file.txt"); writer.Write("Python, Examples!"); writer.Flush();

This code creates a StreamWriter object to write to a file named "file.txt", writes the string "Python, Examples!" to the file, flushes the buffer to ensure that the data is written to the file, and then closes the StreamWriter object.

C# StreamWriter append text

To append text to an existing file using the StreamWriter class in C#, you need to pass a second parameter to the StreamWriter constructor. The second parameter specifies whether to append to an existing file or overwrite it. If you set the second parameter to true, it will append text to the existing file.

using System.IO; StreamWriter writer = new StreamWriter("file.txt", true); writer.WriteLine("This is appended text."); writer.Close();

This code creates a StreamWriter object to write to a file named "file.txt". The second parameter true indicates that the StreamWriter should append to the existing file instead of overwriting it. The WriteLine() method writes a string followed by a line terminator to the file, and the Close() method closes the StreamWriter object.


How to use C# StreamWriter

If the file "file.txt" already exists and contains the text "Python, Examples!", running the above code will append the text "This is appended text." to the end of the file, resulting in the file containing:

Python, Examples! This is appended text.

Note that if the file "file.txt" doesn't exist, the above code will create a new file and write "This is appended text." to it.

Write formatted string using C# StreamWriter

To write formatted strings to a file using the StreamWriter class in C#, you can use the Write() or WriteLine() method along with the String.Format() method.

using System.IO; StreamWriter writer = new StreamWriter("file.txt"); int num1 = 10; int num2 = 20; writer.WriteLine(String.Format("The sum of {0} and {1} is {2}.", num1, num2, num1 + num2)); writer.Close();

In the above code, first create a StreamWriter object to write to a file named "file.txt". Then declare two integer variables num1 and num2, with values of 10 and 20 respectively. The WriteLine() method then writes a formatted string to the file using the String.Format() method. The placeholders {0}, {1}, and {2} correspond to the variables num1, num2, and num1 + num2 respectively.

If you run this code, it will write the following string to the file "file.txt":

The sum of 10 and 20 is 30

You can use various formatting options in the placeholders to control how the variables are formatted in the output string. For example, you can use the {0:C} placeholder to format a number as a currency value, or the {0:D} placeholder to format a number as a decimal value.

using System.IO; StreamWriter writer = new StreamWriter("file.txt"); double num = 1234.56789; writer.WriteLine(String.Format("The value of num is {0:C} and its integer part is {1:D}.", num, (int)num)); writer.Close();

In the above code, declare a double variable num with a value of 1234.56789. The WriteLine() method then writes a formatted string to the file using the {0:C} and {1:D} placeholders. The {0:C} placeholder formats num as a currency value, and the {1:D} placeholder formats the integer part of num as a decimal value.

If you run this code, it will write the following string to the file "file.txt":

The value of num is $1,234.57 and its integer part is 1234.

C# StreamWriter.WriteAsync() method

The WriteAsync() method of the StreamWriter class in C# is an asynchronous method that writes a string to a file. This method returns a Task object that represents the asynchronous write operation.

Following an example of using the WriteAsync() method to write a string to a file asynchronously:

using System.IO; using System.Threading.Tasks; StreamWriter writer = new StreamWriter("file.txt"); string text = "Python, Examples!"; await writer.WriteAsync(text); await writer.FlushAsync(); writer.Close();

In this code, first create a StreamWriter object to write to a file named "file.txt". Then declare a string variable text with a value of "Python, Examples!". The WriteAsync() method writes the string to the file asynchronously, and the FlushAsync() method flushes the buffer to ensure that all the data is written to the file before closing the StreamWriter object.

Note that the await keyword is used before calling the WriteAsync() and FlushAsync() methods. This indicates that the current method should await the completion of the asynchronous write operation before continuing execution.

Using the WriteAsync() method can be beneficial when writing to a file in a UI application or a web application, where the main thread should not be blocked by I/O operations. By using asynchronous I/O operations, the application can continue to be responsive while the write operation is being performed in the background.