从zip文件中的大型txt文件读取文本

时间:2019-01-25 20:04:03

标签: c#

我正在尝试读取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);
                 }
             }
         }
     }

1 个答案:

答案 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作为最简单的解决方案。