C# StreamWriter
is a class that enables you to write text to a file. It is part of the System.IO
namespace and provides various methods for writing data to a file, such as writing individual characters, strings, or arrays of characters.
Here’s an example of how to use StreamWriter
to write text to a file:
using System; using System.IO; class Program { static void Main() { string filePath = "output.txt"; // Create a new instance of StreamWriter and specify the file path. using (StreamWriter writer = new StreamWriter(filePath)) { // Write a string to the file. writer.WriteLine("Hello, world!"); // Write an array of characters to the file. char[] charArray = { 'T', 'e', 's', 't' }; writer.Write(charArray); // Write a formatted string to the file. int number = 42; writer.WriteLine("The answer is {0}.", number); } Console.WriteLine("Text written to the file."); } }
In the example above, we create a new instance of StreamWriter
by passing the file path to its constructor. We use the using
statement to ensure that the StreamWriter
is properly disposed of when we’re done with it.
Inside the using
block, we can use various methods of StreamWriter
to write text to the file. The WriteLine
method writes a string followed by a line terminator, while the Write
method writes an array of characters. You can also use formatting placeholders, such as {0}
, to insert values into the written text.
After executing the code, the specified file (output.txt
in this case) will be created (if it doesn’t exist) and the text will be written to it. Finally, a message is displayed in the console to indicate that the text has been written to the file.
Remember to include the System.IO
namespace at the top of your C# file to use the StreamWriter
class.