从文件读取不够快,我将如何加快速度?
-
03-07-2019 - |
题
这是我阅读文件的方式:
public static string readFile(string path)
{
StringBuilder stringFromFile = new StringBuilder();
StreamReader SR;
string S;
SR = File.OpenText(path);
S = SR.ReadLine();
while (S != null)
{
stringFromFile.Append(SR.ReadLine());
}
SR.Close();
return stringFromFile.ToString();
}
问题是这么久(.txt文件大约是2.5兆)。花了5分多钟。还有更好的方法吗?
采取解决方案
public static string readFile(string path)
{
return File.ReadAllText(path);
}
不到1秒......:)
解决方案
不考虑可怕的变量名称和缺少使用声明(如果有任何例外,你不会关闭文件)应该没问题,当然不应该花5分钟阅读2.5兆。
该文件在哪里?它是在片状网络上吗?
顺便说一下,你正在做的和使用File.ReadAllText之间的唯一区别是你正在丢失换行符。这是故意的吗? ReadAllText需要多长时间?
其他提示
S = SR.ReadLine();
while (S != null)
{
stringFromFile.Append(SR.ReadLine());
}
值得注意的是, S
永远不会在初始 ReadLine()
之后设置,所以 S!= null
条件永远不会触发进入while循环。尝试:
S = SR.ReadLine();
while (S != null)
{
stringFromFile.Append(S = SR.ReadLine());
}
或使用其中一条评论。
如果您需要删除换行符,请使用string.Replace(Environment.NewLine,"")
return System.IO.File.ReadAllText(path);
但我想你可能会错过文件的第一行。试试这个。
S = SR.ReadLine();
while (S != null){
stringFromFile.Append(S);
S = SR.ReadLine();
}
您是否一次需要内存中的整个2.5 Mb?
如果没有,我会尝试使用你需要的东西。
请改用System.IO.File.RealAllLines。
http://msdn.microsoft.com /en-us/library/system.io.file.readalllines.aspx
或者,估计字符数并将其作为容量传递给StringBuilder的构造函数应加快速度。
试试这个,应该快得多:
var str = System.IO.File.ReadAllText(path);
return str.Replace(Environment.NewLine, "");
顺便提一下:下次遇到类似情况时,请尝试预先分配内存。无论您使用何种确切的数据结构,都可以大大改善运行时间。大多数容器( StringBuilder
)都有一个允许你保留内存的构造函数。这样,在读取过程中需要更少的耗时重新分配。
例如,如果要将文件中的数据读入 StringBuilder
,则可以编写以下内容:
var info = new FileInfo(path);
var sb = new StringBuilder((int)info.Length);
(必须播放,因为 System.IO.FileInfo.Length
long
。)
ReadAllText对我来说是一个非常好的解决方案。我在3.000.000行文本文件中使用了以下代码,读取所有行需要4-5秒。
string fileContent = System.IO.File.ReadAllText(txtFilePath.Text)
string[] arr = fileContent.Split('\n');
循环和 StringBuilder
可能是多余的;尝试使用
ReadToEnd 。
要快速阅读文本文件,您可以使用类似这样的内容
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 "";
}
}
希望这会对你有所帮助。有关更多信息,请访问以下链接 - 阅读文本文件的最快方法