2

我似乎无法通过 StreamWriter 将文本写入新创建的 zip 文件(不是 gzip)。我使用 SharpZipLib,但不太明白如何让它工作。DJ Kraze 帮助我将压缩文本文件中的内容流式传输到 StreamReader,我现在尝试相反。我不想先创建一个 csv 文件,然后压缩最终文件,而是想将文本直接流式传输到 zip 容器中要创建的 csv。那可能吗?在我用于获取可与 StreamReader 一起使用的流的片段下方,它只是给出了我在寻找什么的想法,只是这次我想获取与 StreamWriter 一起使用的流。

public static Stream GetZipInputFileStream(string fileName)
{
    ZipInputStream zip = new ZipInputStream(File.OpenRead(fileName));
    FileStream filestream = 
        new FileStream(fileName, FileMode.Open, FileAccess.Read);
    ZipFile zipfile = new ZipFile(filestream);
    ZipEntry item;

    if ((item = zip.GetNextEntry()) != null)
    {
        return zipfile.GetInputStream(item);
    }
    else
    {
        return null;
    }
}

这是我使用它的方式,我基本上是在寻找它,但反过来(StreamWriter -> 新 zip 容器中的新 csv 文件):

using (StreamReader streamReader = Path.GetExtension(fileName).ToUpper().Equals(".ZIP") ? new StreamReader(FileOperations.GetZipInputFileStream(fileName)) : new StreamReader(fileName))
            {
4

2 回答 2

0

此处的第二个示例涉及将流直接写入 SharpZipLib 中的 zip 文件。快速浏览一下,让我们知道它是如何为您工作的。

编辑:由于链接有问题,下面是来自 wiki 的示例。

public void UpdateZipInMemory(Stream zipStream, Stream entryStream, String entryName) 
{

    // The zipStream is expected to contain the complete zipfile to be updated
    ZipFile zipFile = new ZipFile(zipStream);

    zipFile.BeginUpdate();

    // To use the entryStream as a file to be added to the zip,
    // we need to put it into an implementation of IStaticDataSource.
    CustomStaticDataSource sds = new CustomStaticDataSource();
    sds.SetStream(entryStream);

    // If an entry of the same name already exists, it will be overwritten; otherwise added.
    zipFile.Add(sds, entryName);

    // Both CommitUpdate and Close must be called.
    zipFile.CommitUpdate();

    // Set this so that Close does not close the memorystream
    zipFile.IsStreamOwner = false;
    zipFile.Close();

    // Reposition to the start for the convenience of the caller.
    zipStream.Position = 0;
}

以及配套的数据结构

public class CustomStaticDataSource : IStaticDataSource
{
    private Stream _stream;

    // Implement method from IStaticDataSource
    public Stream GetSource() { return _stream; }

    // Call this to provide the memorystream
    public void SetStream(Stream inputStream) 
    {
        _stream = inputStream;
        _stream.Position = 0;
    }
}

如果您可以访问该站点,则有一个调用该代码的示例。

于 2012-02-24T18:10:28.150 回答
0

为此,我最终转储了 SharpZipLib,而是采用了更占用空间的方法,首先解压缩 zip 容器中的所有文件,处理数据,然后将文件移回 zip 容器。如上所述,我面临的问题是我无法一次读取容器中的任何文件,因为它们很大。很高兴看到一个 zip 库将来可能能够处理部分流写入到容器中,但现在我没有看到用 SharpZipLib 完成它的方法。

于 2012-03-03T10:20:49.257 回答