将文本文件读入字符串变量的最快方法是什么?
我理解它可以通过几种方式完成,比如读取单个字节,然后将它们转换为字符串。我在寻找一种编码最少的方法。
将文本文件读入字符串变量的最快方法是什么?
我理解它可以通过几种方式完成,比如读取单个字节,然后将它们转换为字符串。我在寻找一种编码最少的方法。
当前回答
对于那些觉得这个东西有趣和有趣的新手来说,在大多数情况下(根据这些基准测试)将整个文件读入字符串的最快方法是通过以下方法:
using (StreamReader sr = File.OpenText(fileName))
{
string s = sr.ReadToEnd();
}
//you then have to process the string
然而,绝对最快的读取文本文件的整体似乎是以下:
using (StreamReader sr = File.OpenText(fileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
//do what you have to here
}
}
与其他几种技术相比,它在大多数情况下胜出,包括与BufferedReader的竞争。
其他回答
如果你想从应用程序的Bin文件夹中选择文件,那么你可以尝试以下操作,不要忘记做异常处理。
string content = File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"FilesFolder\Sample.txt"));
用最少的c#代码最快的方法可能就是这个:
string readText = System.IO.File.ReadAllText(path);
我在一个ReadAllText和StreamBuffer之间做了一个比较,一个2Mb的csv,它的差异似乎是相当小的,但ReadAllText似乎从完成函数所需的时间占上风。
string contents = System.IO.File.ReadAllText(path)
这是MSDN文档
你可以这样用
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 "";
}
}
希望这对你有所帮助。