从SQL Server Varbinary列创建ZIP文件

时间:2019-05-02 13:21:01

标签: c# .net sql-server .net-4.5

我正在尝试使用控制台应用程序从SQL Server数据库中使用zipArchive下载多个文件。以下代码创建一个空文件。它检索内容并将其添加到MemoryStream。

SqlCommand myCommand;
SqlDataReader reader = null;

using (SqlConnection myConnection = new SqlConnection(connectionString))
{
    string SQL = "select doc_name, doc_content from Documents where id = 200";
    myConnection.Open();
    myCommand = new SqlCommand(SQL.ToString(), myConnection);
    reader = myCommand.ExecuteReader();
    byte[] zipBytes = null;


    using (var compressedFileStream = new MemoryStream())

    using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
    {
        while (reader.Read())
        {
            //Create a zip entry for each attachment
            var zipEntry = zipArchive.CreateEntry(reader["doc_name"].ToString());

            //Get the stream of the attachment
            using (var originalFileStream = new MemoryStream((byte[])reader["doc_content"]))
            using (var zipEntryStream = zipEntry.Open())
            {
                //Copy the attachment stream to the zip entry stream
                originalFileStream.CopyTo(zipEntryStream);
            }
        }

        using (var fileStream = new FileStream(@"C:\test\test.zip", FileMode.Create))
        {
            compressedFileStream.Seek(0, SeekOrigin.Begin);
            compressedFileStream.CopyTo(fileStream);
        }
    }
 }

0 个答案:

没有答案