【发布时间】:2016-08-16 18:22:37
【问题描述】:
我为供应商创建了一个 HTML5 在线门户,他们可以在其中上传和下载任意数量的文件。不幸的是,我不允许向您展示屏幕截图。但问题是: 如果上传了 2 个或更多文件,则程序应创建一个包含所有 PDF 的 .zip 文件。它被正确创建并且文件都在里面,但是它们已损坏,这意味着我无法打开它们。除此之外,他们的文件大小为 1 KB。
String zipFile = String.Format(@"{0}.zip", Guid.NewGuid());
String zipPath = String.Format(@"{0}\{1}", Data.Properties.Settings.Default.DownloadPath, zipFile);
using (FileStream zipToOpen = new FileStream(zipPath, FileMode.CreateNew))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
{
using (SqlConnection con = new SqlConnection(Data.Properties.Settings.Default.SelectionTMPDatabase))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(String.Format("SELECT [FileName], [File] FROM {0} WHERE [DownloadId] = @downloadId", Data.Properties.Settings.Default.SelectionFileDatabaseTable), con))
{
cmd.Parameters.AddWithValue("@downloadId", downloadID);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
if (dr["FileName"] != null && dr["FileName"] != DBNull.Value && fileNames.Contains(dr["FileName"].ToString()))
{
ZipArchiveEntry entry = archive.CreateEntry(dr["FileName"].ToString());
using (StreamWriter writer = new StreamWriter(entry.Open()))
{
writer.Write((byte[])dr["File"]);
}
这是创建 .zip 的部分。我希望你能帮帮我!有什么问题就问吧!
【问题讨论】:
-
我会首先重构以减少嵌套。拆分从数据库中检索数据并将其写入文件
-
你确定
dr["File"]中的字节数组包含所有字节吗?