在.NET中读取文本文件内容到字符串的最佳方法是什么?

Sco*_*nce 4 .net string text-files

看起来应该有比这更短的东西:

private string LoadFromFile(string path)
{
   try
   {
       string fileContents;
       using(StreamReader rdr = File.OpenText(path))
       {
            fileContents = rdr.ReadToEnd();
       }

       return fileContents;
   }
   catch
   {
       throw;
   }
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*mmy 17

首先,标题要求"如何将strnig的内容写入文本文件",但您的代码示例是"如何将文本文件的内容读取到字符串".

回答这两个问题:

using System.IO;
...
string filename = "C:/example.txt";
string content = File.ReadAllText(filename);
File.WriteAllText(filename, content);
Run Code Online (Sandbox Code Playgroud)

另请参阅ReadAllLines/WriteAllLines和ReadAllBytes/WriteAllBytes,而不是您想要字符串数组或字节数组的字符串.


Chr*_*org 5

string text = File.ReadAllText("c:\file1.txt");
File.WriteAllText("c:\file2.txt", text);
Run Code Online (Sandbox Code Playgroud)

另请查看ReadAllLines/WriteAllLines和ReadAllBytes/WriteAllBytes