c# - DotNetZip - 无法访问已关闭的流

标签 c# dotnetzip

类似的问题都不是我要找的!

下面的代码有什么问题? files是文件内容的文本数组,fileNames是对应的文件名数组。

这段代码总是在倒数第二行的 Save 方法失败,但我不明白为什么流会被关闭!

result = new MemoryStream();

using (ZipFile zipFile = new ZipFile())
{
    for (int i = 0; i < files.Count(); i++)
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        Byte[] bytes = encoding.GetBytes(files[i]);
        using (MemoryStream fs = new MemoryStream(bytes))
        {
            zipFile.AddEntry(fileNames[i], fs);
        }
    }
    zipFile.Save(result);
}

感谢您的帮助 - 在这里变得绝望!

这是我基于@spender 的第一条评论的解决方案,尽管他在下面发布的解决方案可能更好。

        try
        {
            result = new MemoryStream();
            List<Stream> streams = new List<Stream>();

            if (files.Count > 0)
            {
                using (ZipFile zipFile = new ZipFile())
                {
                    for (int i = 0; i < files.Count(); i++)
                    {

                        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                        Byte[] bytes = encoding.GetBytes(files[i]);
                        streams.Add(new MemoryStream(bytes));
                        zipFile.AddEntry(fileNames[i], streams[i]);
                    }
                    zipFile.Save(result);
                }
            }
        }
        catch (Exception ex)
        {
            throw;
        }

最佳答案

似乎调用Save 是读取源流的时间点。这意味着您必须在保存之前不对它们进行处理。在这种情况下放弃 using 语句,因为不可能将其范围扩展到循环之外。相反,收集您的 IDisposables 并在保存完成后处理它们。

result = new MemoryStream();

using (ZipFile zipFile = new ZipFile())
{
    List<IDisposable> memStreams = new List<IDisposable>();
    try
    {
        for (int i = 0; i < files.Count(); i++)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            Byte[] bytes = encoding.GetBytes(files[i]);
            MemoryStream fs = new MemoryStream(bytes);
            zipFile.AddEntry(fileNames[i], fs);
            memStreams.Add(fs);
        }
        zipFile.Save(result);
    }
    finally
    {
        foreach(var x in memStreams)
        {
            x.Dispose();
        }
    }
}

关于c# - DotNetZip - 无法访问已关闭的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17583227/

相关文章:

c# - 如何连接具有不同主键/外键的表

c# - Csvhelper v22 不再有定居者?

c# - 从受密码保护的 Zip 文件中提取

c# - 使用 C# 上传到服务器后,Zip 文件已损坏

c# - DotNetZip 取消任务中的提取

c# - ASP.Net 中的数据缓存与 session 对象

c# - LVM_GETCOLUMN 只返回第一列的信息

c# - 修复/替换从 C# 源代码中获取的 xhtml 实体的最佳方法是什么?

c# - ZipFile 弄乱了汉字

c# - DotNetZip 从其他 zip 的子集创建 zip