使用SharpZipLib压缩多个文件并放在一个字符串中

时间:2014-10-22 15:53:37

标签: c# .net zip memorystream sharpziplib

我一直使用 SharpZipLib 在我的ASP.NET应用程序中创建zip文件,我发现它是一个非常好的库。但是在Web应用程序中,我总是将zip文件的流用作http响应的OutPutStream(Response.OutputStream),它直接将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;

1 个答案:

答案 0 :(得分:1)

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

Convert.ToBase64String(byte[])Convert.FromBase64String(byte[])应该做到这一点。

相关问题