gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:34:50 25 4
gpt4 key购买 nike

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

最佳答案

第二个例子here地址直接从 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;
}
}

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

关于c# - SharpZipLib 无法使用 StreamWriter 将文本写入新创建的 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9435691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com