write to a file in csharp

To write to a file in C#, you first need to create a new instance of a StreamWriter class. This class provides you with the necessary methods to write to a file.

Here's an example of how to write a string to a file in C#:

main.cs
using System.IO;
using System.Text;

string filePath = "C:\\path\\to\\file.txt";
string textToWrite = "Hello, world!";

using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
using (StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8))
{
    streamWriter.Write(textToWrite);
}
333 chars
12 lines

In the code above, we first declare the file path and text to write. We then create a new FileStream object with the file path, FileMode.Create means it will create a new file if it does not exist or overwrite if it does exist, and FileAccess.Write because we want to write to the file.

Then we create a new StreamWriter object and pass the FileStream object and Encoding. The Encoding specifies the character encoding of the file. In this example, we use UTF8.

Finally, we write the text using the streamWriter.Write() method. Note that this is a synchronous operation, which means it will block the current thread until the write operation is completed.

It's best practice to wrap the file stream and stream writer in a using statement, which ensures that the resources used by the objects are properly disposed of once the write operation is completed.

gistlibby LogSnag