使用 System.IO.Packaging 在 C# 中创建 zip

发布于 2024-11-19 12:06:17 字数 2211 浏览 1 评论 0原文

我正在尝试在服务器上动态创建 zip 文件,其中包含来自在线服务的照片。但是当我尝试打开该文件时,WinRar 说该文件格式未知或已损坏。

这是代码:

MemoryStream stream = new MemoryStream();
Package package = ZipPackage.Open(stream, FileMode.Create, FileAccess.ReadWrite);

foreach (Order o in orders)
{
    o.GetImages();

    Parallel.ForEach(o.Images, (Dictionary<string, object> image) =>
    {
        string imageId = (string)image["ID"];
        int orderId = (int)image["OrderId"];
        string fileName = (string)image["FileName"];
        string url = (string)image["URL"];

        if (string.IsNullOrEmpty(fileName))
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            byte[] data = wc.DownloadData(url);
            MemoryStream ms = new MemoryStream(data);
            ms.Write(data, 0, data.Length);

            string ext;

            switch(wc.ResponseHeaders["Content-Type"])
            {
                case "image/jpeg":
                case "image/jpg":
                ext = "jpg";
                    break;

                case "image/png":
                    ext = "png";
                    break;

                case "image/gif":
                    ext = "gif";
                    break;

                default :
                    ext = "un";
                    break;
            }

            Uri uri = new Uri("/" + orderId.ToString() + "/" + imageId + "." + ext, UriKind.Relative);

            var part = package.CreatePart(uri, wc.ResponseHeaders["Content-Type"], CompressionOption.NotCompressed);

            var pstream = part.GetStream(FileMode.Open, FileAccess.ReadWrite);

            pstream.Write(data, 0, data.Length);

            var rel = package.CreateRelationship(part.Uri, TargetMode.Internal, "http://example.com/AlbumImage");


        }
    });
}

package.Flush();

byte[] fileBytes = new byte[stream.Length];
stream.Read(fileBytes, 0, Convert.ToInt32(stream.Length));

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=Orders.zip");
Response.AddHeader("Content-Length", stream.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(fileBytes);
Response.End();

I am trying to create zip file dynamically on the server that includes photos from online services. But when I try to open the file, WinRar sais the the file is unknown format or damaged.

this is the code:

MemoryStream stream = new MemoryStream();
Package package = ZipPackage.Open(stream, FileMode.Create, FileAccess.ReadWrite);

foreach (Order o in orders)
{
    o.GetImages();

    Parallel.ForEach(o.Images, (Dictionary<string, object> image) =>
    {
        string imageId = (string)image["ID"];
        int orderId = (int)image["OrderId"];
        string fileName = (string)image["FileName"];
        string url = (string)image["URL"];

        if (string.IsNullOrEmpty(fileName))
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            byte[] data = wc.DownloadData(url);
            MemoryStream ms = new MemoryStream(data);
            ms.Write(data, 0, data.Length);

            string ext;

            switch(wc.ResponseHeaders["Content-Type"])
            {
                case "image/jpeg":
                case "image/jpg":
                ext = "jpg";
                    break;

                case "image/png":
                    ext = "png";
                    break;

                case "image/gif":
                    ext = "gif";
                    break;

                default :
                    ext = "un";
                    break;
            }

            Uri uri = new Uri("/" + orderId.ToString() + "/" + imageId + "." + ext, UriKind.Relative);

            var part = package.CreatePart(uri, wc.ResponseHeaders["Content-Type"], CompressionOption.NotCompressed);

            var pstream = part.GetStream(FileMode.Open, FileAccess.ReadWrite);

            pstream.Write(data, 0, data.Length);

            var rel = package.CreateRelationship(part.Uri, TargetMode.Internal, "http://example.com/AlbumImage");


        }
    });
}

package.Flush();

byte[] fileBytes = new byte[stream.Length];
stream.Read(fileBytes, 0, Convert.ToInt32(stream.Length));

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=Orders.zip");
Response.AddHeader("Content-Length", stream.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(fileBytes);
Response.End();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谷夏 2024-11-26 12:06:17

这都是关于帕克·乌里斯的。我们也被他们打过。这是在 zip 中存储两个文件的工作示例。代码刚刚从我们的项目复制,并删除了一些私人数据。

           var dataFilePath = Path.GetFileName(dataFileName);
           var dataFileUri = PackUriHelper.CreatePartUri(new Uri(dataFilePath, UriKind.Relative));
            // Create the Package
            using (var package = Package.Open(filePath, FileMode.Create))
            {
                // Add the diagram view part to the Package
                var pkgPart = package.CreatePart(dataFileUri, MediaTypeNames.Application.Octet);
                var pkgStream = pkgPart.GetStream();

                // Copy the data to the model view part
                // diagramFileName Encoding.Default.GetBytes(text)
                using (var modelStream = new FileStream(dataFileName, FileMode.Open, FileAccess.Read))
                {
                    const int bufSize = 0x1000;
                    var buf = new byte[bufSize];
                    int bytesRead;
                    while ((bytesRead = modelStream.Read(buf, 0, bufSize)) > 0)
                    {
                        pkgStream.Write(buf, 0, bytesRead);
                    }
                }

                // Add a context Part to the Package
                var pkgPartContext = package.CreatePart(ctxUri, MediaTypeNames.Application.Octet);
                var ctxPkgStream = pkgPartContext.GetStream();

                // Copy the data to the context part
                using (var ctxStream = new FileStream(ctxFileName, FileMode.Open, FileAccess.Read))
                {
                    const int bufSize = 0x1000;
                    var buf = new byte[bufSize];
                    int bytesRead;
                    while ((bytesRead = ctxStream.Read(buf, 0, bufSize)) > 0)
                    {
                        ctxPkgStream.Write(buf, 0, bytesRead);
                    }
                }
            }

            // remove tmp files
            File.Delete(ctxFileName);
            File.Delete(dataFileName);

It's all about Pack Uris. We also have been beaten by them. Here is working sample for storing two files in zip. Code just copied from our project with removing some private data.

           var dataFilePath = Path.GetFileName(dataFileName);
           var dataFileUri = PackUriHelper.CreatePartUri(new Uri(dataFilePath, UriKind.Relative));
            // Create the Package
            using (var package = Package.Open(filePath, FileMode.Create))
            {
                // Add the diagram view part to the Package
                var pkgPart = package.CreatePart(dataFileUri, MediaTypeNames.Application.Octet);
                var pkgStream = pkgPart.GetStream();

                // Copy the data to the model view part
                // diagramFileName Encoding.Default.GetBytes(text)
                using (var modelStream = new FileStream(dataFileName, FileMode.Open, FileAccess.Read))
                {
                    const int bufSize = 0x1000;
                    var buf = new byte[bufSize];
                    int bytesRead;
                    while ((bytesRead = modelStream.Read(buf, 0, bufSize)) > 0)
                    {
                        pkgStream.Write(buf, 0, bytesRead);
                    }
                }

                // Add a context Part to the Package
                var pkgPartContext = package.CreatePart(ctxUri, MediaTypeNames.Application.Octet);
                var ctxPkgStream = pkgPartContext.GetStream();

                // Copy the data to the context part
                using (var ctxStream = new FileStream(ctxFileName, FileMode.Open, FileAccess.Read))
                {
                    const int bufSize = 0x1000;
                    var buf = new byte[bufSize];
                    int bytesRead;
                    while ((bytesRead = ctxStream.Read(buf, 0, bufSize)) > 0)
                    {
                        ctxPkgStream.Write(buf, 0, bytesRead);
                    }
                }
            }

            // remove tmp files
            File.Delete(ctxFileName);
            File.Delete(dataFileName);
上课铃就是安魂曲 2024-11-26 12:06:17

我知道这个问题有点老了,但我也遇到过类似的问题。我用过

stream.Seek(0, SeekOrigin.Begin);

并且有效

I know that this question is a bit old but I had a similar problem. I used

stream.Seek(0, SeekOrigin.Begin);

and it worked

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文