C#里面有多个Word文档创建Zip

时间:2015-12-10 15:23:58

标签: c# file download stream zip

目前仍然存在一个损坏的.zip文件夹,其中包含我认为正确的内容(尺寸增加,因为我包含了更多的单词doc)。

不确定为什么它会破坏拉链 - 它会合理地生成word文档,因为这是我以前的实现并且没有改变。

private void GenReport(List<PerformanceReport> performanceReportData2, string start, string end)
        {
            List<byte[]> byteList = new List<byte[]>();

            var document = Server.MapPath("~/Content/docs/Performance Report.docx");
            var byteArray = System.IO.File.ReadAllBytes(document);

            // Format parameters
            var startRange = DateTime.Parse(start);
            var endRange = DateTime.Parse(end);
            foreach (var performanceReportData in performanceReportData2)
            {
                var trust = performanceReportData.Name.Replace(",", string.Empty);
                trust = trust.Replace("&", string.Empty);
                start = start.Replace("/", "-");
                end = end.Replace("/", "-");

                using (var stream = new MemoryStream())
                {
                    stream.Write(byteArray, 0, byteArray.Length);

                    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
                    {
                        var body = wordDoc.MainDocumentPart;
                        ....... Do stuff
                        body.Document.Save();
                        byteList.Add(stream.ToArray());
                    }
                }
            }

            using (var ms = new MemoryStream())
            {
                using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
                {
                    foreach (var attachment in byteList)
                    {
                        var entry = zipArchive.CreateEntry("test.docx");

                        using (var originalFile = new MemoryStream(attachment))
                        {
                            using (var zipEntryStream = entry.Open())
                            {
                                originalFile.CopyTo(zipEntryStream);
                            }
                        }
                    }

                    Response.ContentType = "application/zip";
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + "Performance Report.zip");
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.CopyTo(Response.OutputStream);
                    Response.End();
                }
            }
        }

我已经完成了为什么它会破坏Zip文件夹的想法 - 如果我在文本编辑器中打开zip文件夹,它以PK开头,我收集确认它是一个Zip。

1 个答案:

答案 0 :(得分:0)

我的范围不正确。

工作代码如下所示

Node node1 = nl1.item(0);