SharpZipLib无法使用StreamWriter将文本写入新创建的csv文件

本文关键字:新创建 创建 文件 csv StreamWriter 文本 SharpZipLib | 更新日期: 2023-09-27 18:25:47

我似乎无法通过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))
            {

SharpZipLib无法使用StreamWriter将文本写入新创建的csv文件

这里的第二个例子解决了从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;
    }
}

这里有一个例子,如果你能接通网站,就可以调用该代码。

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