建立在C#中的zip与System.IO.Packaging程序 [英] Creating zip in c# with System.IO.Packaging

查看:379
本文介绍了建立在C#中的zip与System.IO.Packaging程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,其中包括来自在线服务的照片在服务器上动态地创建zip文件。但是,当我尝试打开该文件时,WinRAR的最高审计机关的文件为未知格式或损坏



这是代码:

  MemoryStream的流=新的MemoryStream(); 
套餐包= ZipPackage.Open(流FileMode.Create,FileAccess.ReadWrite);

的foreach(阶为O订单)
{
o.GetImages();

Parallel.ForEach(o.Images,(字典<字符串对象>图片)=>
{
串imageId =(字符串)图像[ID];
INT订单ID =(int)的图像[的OrderId];
字符串文件名=(字符串)图像[文件名];
字符串URL =(字符串)图像[网址] ;

如果(string.IsNullOrEmpty(文件名))
{
System.Net.WebClient WC =新System.Net.WebClient();
字节[]数据= wc.DownloadData(URL);
的MemoryStream毫秒=新的MemoryStream(数据);
ms.Write(数据,0,data.Length);

线转;

开关(wc.ResponseHeaders [的Content-Type])
{
案图像/ JPEG:
案图像/ JPG:
分机=JPG;
中断;

案图像/ PNG:
分机=PNG;
中断;

案图像/ GIF:
分机=GIF;
中断;

默认:
分机=UN;
中断;
}

乌里URI =新的URI(/+ orderId.ToString()+/+ imageId + +分机,UriKind.Relative。);

VAR部分= package.CreatePart(URI,wc.ResponseHeaders [内容类型],CompressionOption.NotCompressed);

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

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

VAR相对= package.CreateRelationship(part.Uri,TargetMode.Internal,http://example.com/AlbumImage);


}
});
}

package.Flush();

字节[] = fileBytes新的字节[stream.Length]
stream.Read(fileBytes,0,Convert.ToInt32(stream.Length));

Response.Clear();
Response.AddHeader(内容处置,附件;文件名= Orders.zip);
Response.AddHeader(内容长度,stream.Length.ToString());
Response.ContentType =应用程序/八位字节流;
Response.BinaryWrite(fileBytes);
到Response.End();


解决方案

这是所有关于包的URI。我们也被他们殴打。下面是存储在压缩两个文件的工作样本。代码只是从我们的项目复制与删除一些私人数据。

  VAR dataFilePath = Path.GetFileName(dataFileName); 
VAR dataFileUri = PackUriHelper.CreatePartUri(新的URI(dataFilePath,UriKind.Relative));
//使用(VAR包= Package.Open(文件路径,FileMode.Create))
{
//包
添加图表视图部分包
VAR pkgPart = package.CreatePart(dataFileUri,MediaTypeNames.Application.Octet);
VAR pkgStream = pkgPart.GetStream();

//数据使用复制到模型视图的一部分
// diagramFileName Encoding.Default.GetBytes(文本)
(VAR modelStream =新的FileStream(dataFileName,FileMode.Open ,FileAccess.Read))
{
const int的由bufSize = 0x1000的;
变种BUF =新的字节[由bufSize]
INT读取动作;
而((读取动作= modelStream.Read(BUF,0,由bufSize))大于0)
{
pkgStream.Write(BUF,0,读取动作);
}
}

//添加上下文本部包
VAR pkgPartContext = package.CreatePart(ctxUri,MediaTypeNames.Application.Octet);
VAR ctxPkgStream = pkgPartContext.GetStream();

//数据使用复制上下文部分
(VAR ctxStream =新的FileStream(ctxFileName,FileMode.Open,FileAccess.Read))
{
常量INT由bufSize = 0x1000的;
变种BUF =新的字节[由bufSize]
INT读取动作;
而((读取动作= ctxStream.Read(BUF,0,由bufSize))大于0)
{
ctxPkgStream.Write(BUF,0,读取动作);
}
}
}

//删除tmp文件,
File.Delete(ctxFileName);
File.Delete(dataFileName);


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();

解决方案

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);

这篇关于建立在C#中的zip与System.IO.Packaging程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆