我正在尝试读取ZIP文件中TXT文件的所有文本。解压缩后的文件有1GB。 以下代码不会引发错误,但永远不会结束,是否有任何方法可以加快该过程?
var fileText = string.Empty;
using (var file = File.OpenRead(System.Configuration.ConfigurationManager.AppSettings["zipPath"]))
using (var zip = new ZipArchive(file, ZipArchiveMode.Read))
{
using (var stream = zip.Entries.First().Open())
{
using (var streamReader = new StreamReader(stream))
{
try
{
while (streamReader.Peek() >= 0)
{
var line = streamReader.ReadLine();
fileText = fileText + line;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
答案 0 :(得分:0)
尝试:
var fileText = string.Empty;
using (var file = File.OpenRead(System.Configuration.ConfigurationManager.AppSettings["zipPath"]))
using (var zip = new ZipArchive(file, ZipArchiveMode.Read))
{
using (var stream = zip.Entries.First().Open())
{
using (var streamReader = new StreamReader(stream))
{
try
{
while (!streamReader.EndOfStream)
{
var line = streamReader.ReadLine();
fileText = fileText + line;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
但是,请考虑使用ReadAllLines
作为最简单的解决方案。