Curriculum
In C#, the StreamWriter class is used to write text to a file in a high-level, sequential manner. It provides methods for writing strings, characters, and lines of text to a file, as well as methods for flushing and closing the stream.
Here is an example of using StreamWriter to write text to a file:
using System.IO; class Program { static void Main() { string filePath = "example.txt"; string text = "Hello, World!"; using (StreamWriter writer = new StreamWriter(filePath)) { writer.WriteLine(text); } } }
In this example, we create a StreamWriter object by specifying the file path. We then use the WriteLine method to write a line of text to the file. The WriteLine method automatically adds a newline character to the end of the text, so each call to WriteLine writes a new line to the file.
Here is an example of using StreamWriter to append text to an existing file:
using System.IO; class Program { static void Main() { string filePath = "example.txt"; string text = "Hello, World!"; using (StreamWriter writer = new StreamWriter(filePath, true)) { writer.WriteLine(text); } } }
In this example, we create a StreamWriter object by specifying the file path and setting the append parameter to true. This causes the StreamWriter to append the text to the end of the file instead of overwriting it.
Overall, StreamWriter is a useful class for writing text to files in C#. It provides a high-level, convenient way to write text to files, but it does not provide the low-level control and efficiency of FileStream. It also requires careful attention to detail and proper error handling to ensure that files are written correctly.