将文本文件读入字符串变量的最快方法是什么?

我理解它可以通过几种方式完成,比如读取单个字节,然后将它们转换为字符串。我在寻找一种编码最少的方法。


当前回答

File怎么样?ReadAllText:

string contents = File.ReadAllText(@"C:\temp\test.txt");

其他回答

File怎么样?ReadAllText:

string contents = File.ReadAllText(@"C:\temp\test.txt");

你也可以从文本文件中读取文本到字符串,如下所示

string str = "";
StreamReader sr = new StreamReader(Application.StartupPath + "\\Sample.txt");
while(sr.Peek() != -1)
{
  str = str + sr.ReadLine();
}

你可以这样用

public static string ReadFileAndFetchStringInSingleLine(string file)
    {
        StringBuilder sb;
        try
        {
            sb = new StringBuilder();
            using (FileStream fs = File.Open(file, FileMode.Open))
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using (StreamReader sr = new StreamReader(bs))
                    {
                        string str;
                        while ((str = sr.ReadLine()) != null)
                        {
                            sb.Append(str);
                        }
                    }
                }
            }
            return sb.ToString();
        }
        catch (Exception ex)
        {
            return "";
        }
    }

希望这对你有所帮助。

用最少的c#代码最快的方法可能就是这个:

string readText = System.IO.File.ReadAllText(path);

string text = File.ReadAllText("Path");一个字符串变量中包含了所有文本。如果你需要每一行单独,你可以使用这个:

string[] lines = File.ReadAllLines("Path");