create a text file in csharp

To create a text file in C#, you can use the following code:

main.cs
using System.IO;

string filePath = @"C:\example\textfile.txt";
string fileContent = "This is an example text to write to the file.";

// Create the file and write the content to it.
using (StreamWriter writer = new StreamWriter(filePath))
{
    writer.Write(fileContent);
}
275 chars
11 lines

In this code, we are using the StreamWriter class to create the file and write the content to it. First, we define the file path and the content that we want to write. Then, we use the StreamWriter class to create the file and write the content to it using the Write method. Finally, we wrap the StreamWriter object into a using statement to ensure that the file is closed and disposed of properly after use.

gistlibby LogSnag