使用 System.IO.File 类写入文件

你可以使用 System.IO.File.WriteAllText 函数将字符串写入文件。

string text = "String that will be stored in the file";
System.IO.File.WriteAllText(@"C:\MyFolder\OutputFile.txt", text);

你还可以使用 System.IO.File.WriteAllLines 函数接收 IEnumerable<String> 作为第二个参数(与前一个示例中的单个字符串相对)。这使你可以从一系列行中写入内容。

string[] lines = { "My first string", "My second string", "and even a third string" };
System.IO.File.WriteAllLines(@"C:\MyFolder\OutputFile.txt", lines);