如何创建和使用ASP.NET填写一个ZIP文件? [英] How to create and fill a ZIP file using ASP.NET?

查看:240
本文介绍了如何创建和使用ASP.NET填写一个ZIP文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要将一些文件打包动态为.zip创建一个SCORM包,谁知道如何可以做到这一点使用code?是否有可能建立动态的.zip内的文件夹结构呢?

Need to dynamically package some files into a .zip to create a SCORM package, anyone know how this can be done using code? Is it possible to build the folder structure dynamically inside of the .zip as well?

推荐答案

您不必再使用外部库。 System.IO.Packaging程序具有可用于删除内容转换成一个zip文件的类。它不是简单的,但是。 <一href=\"http://weblogs.asp.net/jongalloway//creating-zip-archives-in-net-without-an-external-library-like-sharpziplib\"相对=nofollow>这里有一个博客帖子有一个例子(其末;挖掘吧)

You don't have to use an external library anymore. System.IO.Packaging has classes that can be used to drop content into a zip file. Its not simple, however. Here's a blog post with an example (its at the end; dig for it).

链接并不稳定,所以这里的乔恩在帖子中提供的例子。

The link isn't stable, so here's the example Jon provided in the post.

using System;
using System.IO;
using System.IO.Packaging;

namespace ZipSample
{
    class Program
    {
        static void Main(string[] args)
        {
            AddFileToZip("Output.zip", @"C:\Windows\Notepad.exe");
            AddFileToZip("Output.zip", @"C:\Windows\System32\Calc.exe");
        }

        private const long BUFFER_SIZE = 4096;

        private static void AddFileToZip(string zipFilename, string fileToAdd)
        {
            using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
            {
                string destFilename = ".\\" + Path.GetFileName(fileToAdd);
                Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
                if (zip.PartExists(uri))
                {
                    zip.DeletePart(uri);
                }
                PackagePart part = zip.CreatePart(uri, "",CompressionOption.Normal);
                using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
                {
                    using (Stream dest = part.GetStream())
                    {
                        CopyStream(fileStream, dest);
                    }
                }
            }
        }

        private static void CopyStream(System.IO.FileStream inputStream, System.IO.Stream outputStream)
        {
            long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;
            byte[] buffer = new byte[bufferSize];
            int bytesRead = 0;
            long bytesWritten = 0;
            while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                outputStream.Write(buffer, 0, bytesRead);
                bytesWritten += bytesRead;
            }
        }
    }
}

这篇关于如何创建和使用ASP.NET填写一个ZIP文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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