代码之家  ›  专栏  ›  技术社区  ›  Scott Lawrence

在.NET中将文本文件的内容读入字符串的最佳方式是什么?

  •  4
  • Scott Lawrence  · 技术社区  · 18 年前

    private string LoadFromFile(string path)
    {
       try
       {
           string fileContents;
           using(StreamReader rdr = File.OpenText(path))
           {
                fileContents = rdr.ReadToEnd();
           }
    
           return fileContents;
       }
       catch
       {
           throw;
       }
    }
    
    4 回复  |  直到 17 年前
        1
  •  17
  •   Jimmy    18 年前

    首先,标题要求“如何将strnig的内容写入文本文件”

    对两个问题的答复:

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

    如果需要字符串数组或字节数组而不是字符串,请参见ReadAllLines/WriteAllLines和ReadAllBytes/WriteAllBytes。

        2
  •  5
  •   Chris Marasti-Georg Scott Weinstein    18 年前
    string text = File.ReadAllText("c:\file1.txt");
    File.WriteAllText("c:\file2.txt", text);
    

    还可以查看ReadAllLines/WriteAllines和ReadAllBytes/WriteAllBytes

        3
  •  4
  •   Bjorn Reppen    18 年前

    这个异常处理程序没有意义。它什么也不做。这只是您的代码的简短版本,很好:

     private string LoadFromFile(string path)
     {
        using(StreamReader rdr = File.OpenText(path))
          return rdr.ReadToEnd();
     }
    
        4
  •  3
  •   Brad Wilson    18 年前

    ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_mscorlib/html/4803f846-3d8a-de8a-18eb-32cfcd038f76.htm 如果您安装了VS2008的帮助。