【问题标题】:How can I write blob datas to zip and download it in C#? [closed]如何将 blob 数据写入 zip 并在 C# 中下载? [关闭]
【发布时间】:2013-10-09 00:36:24
【问题描述】:

假设我从数据库中得到了一些 blob。 然后我把它们放在字节数组中。例如:

Byte[] lol1=(Byte[])reader["data1"];
Byte[] lol2=(Byte[])reader["data2"];

现在我如何将这些字节数组作为文件写入 zip 并从 C# 中的浏览器下载为文件?

// 为清楚起见进行编辑

“Manager.cs”文件中的相关代码如:

    public Byte[] FileDownload(string userName)
    {
        try
        {
            MySqlDataReader reader = new MySqlCommand("SELECT veri FROM veriler WHERE kullanici_id = (SELECT id FROM uyeler WHERE kullanici_adi='" + userName + "')", con).ExecuteReader();
            MemoryStream ms = new MemoryStream();
            GZipStream gzs = new GZipStream(ms, CompressionMode.Compress);
            while (reader.Read())
                gzs.Write((Byte[])reader["veri"], 0, ((Byte[])reader["veri"]).Length);
            return ms.ToArray();
        }
        catch (Exception)
        {
            return Encoding.UTF8.GetBytes(string.Empty);
        }
    }

“DataDown.aspx.cs”文件中的相关代码如:

protected void download_Click(object sender, EventArgs e)
{
    Response.AddHeader("Content-type", ContentType);
    Response.AddHeader("Content-Disposition", "attachment; filename=Archive.zip");
    Response.BinaryWrite(new Manager().FileDownload(Session["user"].ToString()));
    Response.Flush();
    Response.End();
}

它返回一个 .zip 文件,该文件是其中唯一的文件。它必须是两个文件。而且,这一个文件已损坏。

【问题讨论】:

  • 你有没有尝试过这样做?
  • 查看已编辑的问题。

标签: c# file zip bytearray blob


【解决方案1】:

要干净利落地执行此操作,您需要 System.IO.Compression,它仅在 .Net 4.5 forward 中可用。

string blobName = "data1";
string zipName = "database.zip";
Byte[] blob = (Byte[])reader[blobName];

using(MemoryStream zs = new MemoryStream())
{
  // Build the archive
  using(System.IO.Compression.ZipArchive zipArchive = new ZipArchive(zs, ZipArchiveMode.Create, true))
  {
    System.IO.Compression.ZipArchiveEntry archiveEntry = zipArchive.CreateEntry(blobName);
    using(Stream entryStream = archiveEntry.Open())
    {
      entryStream.Write(blob, 0/* offset */, blob.Length);
    }
  }

  //Rewind the stream for reading to output.
  zs.Seek(0,SeekOrigin.Begin);

  // Write to output.
  Response.Clear();
  Response.ContentType = "application/zip";
  Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", zipName));
  Response.BinaryWrite(zs.ToArray());
  Response.End();
 }

如果您的数据提供程序支持将 blob 作为流打开,您可能可以避免将条目读取到缓冲区中,而是使用 Stream.CopyTo()

【讨论】:

  • 我使用了 GZipStream 类。 System.IO.Compression 在我的编译器中没有 ZipArchiveEntry 类。我正在使用 MS Visual Studio 2012。我猜它的框架版本是 .Net 4.5。我编辑了我的问题。你可以看。感谢您的回答。
  • 存在于 .net 4.5 中。只需确保在项目中包含对 System.IO.Compression.dll 的引用。 msdn.microsoft.com/ru-ru/library/…
  • 我添加了它,您的代码对我有用。谢谢兄弟。
猜你喜欢
  • 1970-01-01
  • 2023-01-03
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多