是否可以在压缩的txt文件上使用System.IO.File.ReadAllLines而不解压它?
我找到了一些包括提取和删除文件的解决方案,但我真的更愿意避免这种解决方案。
这是一个控制台应用程序,应该为您指明方向:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;
namespace ZipExploration
{
class Program
{
static void Main(string[] args)
{
getFileList(@"C:\errors\myfiles.zip");
Console.ReadLine();
}
static List<string> getFileList(string zip)
{
List<string> retVal = new List<string>();
try
{
if (!File.Exists(zip))
{
Console.WriteLine(@"File does not exist");
}
//FileInfo fi = new FileInfo(zip);
//using (MemoryStream ms = new MemoryStream())
using( FileStream ms = File.Create(@"C:\Errors\myfile.txt"))
{
using (FileStream fs = new FileStream(zip,FileMode.Open))
{
using (ZipArchive arc = new ZipArchive(fs,ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry e in arc.Entries)
{
retVal.Add(e.FullName);
Console.WriteLine(e.FullName);
getContents(e);
}
}
}
ms.Close();
//byte[] buffer = ms.ToArray();
//Console.WriteLine(buffer.Length);
//Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return retVal;
}
static void getContents(ZipArchiveEntry e)
{
using (StreamReader stm = new StreamReader( e.Open()))
{
Console.WriteLine(stm.ReadToEnd());
}
}
}
}
您可以使用 BoxedApp SDK 创建一个虚拟目录并将 zip 文件的内容提取到该目录。不会在磁盘上写入任何文件。还有NI.Vfs库,不过我没用过
using System.IO.Compression;
var filename = "sample.zip";
var findext = ".txt";
List<string>? data = null;
using (var zip = ZipFile.OpenRead(filename))
{
foreach(var entry in zip.Entries)
{
if (entry.FullName.EndsWith(findext, StringComparison.OrdinalIgnoreCase))
{
using (var reader = new StreamReader(entry.Open()))
{
data = reader.ReadToEnd().Split(Environment.NewLine).ToList();
}
}
}
}