【问题标题】:Zip several files with SharpZipLib and place inside a string使用 SharpZipLib 压缩几个文件并放在一个字符串中
【发布时间】:2014-10-22 15:53:36
【问题描述】:

我一直使用 SharpZipLib 在我的 ASP.NET 应用程序中创建 zip 文件,我发现它是一个非常好的库。然而,在 Web 应用程序中,我总是将 http 响应 (Response.OutputStream) 的 OutPutStream 用作 zip 文件的流,它直接将 zip 文件传递​​给用户。

现在我需要创建一个 zip“文件”,但不是将其发送到 Response.OutputStream,而是需要将其作为方法的字符串返回值发送。但是,我尝试保存的 zip 文件总是损坏。最后一步,转换字符串并保存为zip文件的流程对于以这种格式获得的其他zip文件是正确的,因此错误必须在下面显示的方法中:

MemoryStream outputMemoryStream = new MemoryStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(outputMemoryStream);
zipOutputStream.SetLevel(3);
Encoding isoEncoding = Encoding.GetEncoding(28591);

int nfiles = 10;

for (var fileId=0; i<nfiles;i++)
{
  using (var inputMemoryStream = new MemoryStream())
  {
    inputMemoryStream.Position = 0;

    string fileContent = GetFileContent(fileId);

    inputMemoryStream.Write(isoEncoding.GetBytes(fileContent), 0, filecontent.Length);

    var newEntry = new ZipEntry("file_" + fileId + ".xml");
    newEntry.DateTime = DateTime.Now;

    zipOutputStream.PutNextEntry(newEntry);

    inputMemoryStream.Position = 0;

    StreamUtils.Copy(inputMemoryStream, zipOutputStream, new byte[4096]);
    zipOutputStream.CloseEntry(); 
  }
}

zipOutputStream.IsStreamOwner = false;
zipOutputStream.Finish();
zipOutputStream.Close();
zipOutputStream.Dispose();

outputMemoryStream.Position = 0;

var sr = new StreamReader(ms);
string zipFileString = sr.ReadToEnd();

return zipFileString;

【问题讨论】:

    标签: c# .net zip memorystream sharpziplib


    【解决方案1】:

    尝试使用 Base64 将 byte[] 转换为编码字符串。

    Convert.ToBase64String(byte[]) Convert.FromBase64String(byte[]) 应该可以解决问题。

    【讨论】:

    • 谢谢!我猜当将未编码的字符串返回给客户端时,字节变得混乱了。使用编码可以保证字节序列不会被破坏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多