当前位置:编程学习 > C#/ASP.NET >>

请教个创建zip文件的问题

请教个创建zip文件的问题

我在网上找了一下,始终没有找到一个合适的创建zip文件的方法。
使用ZipPackage类产生的文件包含几个其他的文件,感觉不舒服,使用GZipStream创建的好像也不是标准的zip文件,使用windows自身的解压功能好像解压不了。

不知道哪位高手能够指教一下,我就是想能够自己将两个文件包在一个标准的zip文件中。 --------------------编程问答-------------------- 使用 ICSharpCode.SharpZipLib

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Diagnostics;
using ICSharpCode.SharpZipLib.Core;

namespace TestConsole
{
    class Program
    {
        static void Main()
        {
            //CreateZipFile(@"d:\", @"d:\a.zip");
            UnZipFile(@"d:\a.zip");

            Console.Read();
        }

        private static void CreateZipFile(string filesPath, string zipFilePath)
        {

            if (!Directory.Exists(filesPath))
            {
                Console.WriteLine("Cannot find directory '{0}'", filesPath);
                return;
            }

            try
            {
                string[] filenames = Directory.GetFiles(filesPath);
                using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
                {

                    s.SetLevel(9); // 压缩级别 0-9
                    //s.Password = "123"; //Zip压缩文件密码
                    byte[] buffer = new byte[4096]; //缓冲区大小
                    foreach (string file in filenames)
                    {
                        ZipEntry entry = new ZipEntry(Path.GetFileName(file));
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);
                        using (FileStream fs = File.OpenRead(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }
                    s.Finish();
                    s.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception during processing {0}", ex);
            }
        }

        private static void UnZipFile( string zipFilePath)
        {
            if (!File.Exists(zipFilePath))
            {
                Console.WriteLine("Cannot find file '{0}'", zipFilePath);
                return;
            }

            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
            {

                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {

                    Console.WriteLine(theEntry.Name);

                    string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    // create directory
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(theEntry.Name))
                        {

                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}
--------------------编程问答-------------------- 这个是需要用那个第三方组件,我想直接用。net自身的。 --------------------编程问答-------------------- //  -------------------------- CreatePackage --------------------------
/// <summary>
///   Creates a package zip file containing specified
///   content and resource files.</summary>
private static void CreatePackage()
{
    // Convert system path and file names to Part URIs. In this example
    // Uri partUriDocument /* /Content/Document.xml */ =
    //     PackUriHelper.CreatePartUri(
    //         new Uri("Content\Document.xml", UriKind.Relative));
    // Uri partUriResource /* /Resources/Image1.jpg */ =
    //     PackUriHelper.CreatePartUri(
    //         new Uri("Resources\Image1.jpg", UriKind.Relative));
    Uri partUriDocument = PackUriHelper.CreatePartUri(
                              new Uri(documentPath, UriKind.Relative));
    Uri partUriResource = PackUriHelper.CreatePartUri(
                              new Uri(resourcePath, UriKind.Relative));

    // Create the Package
    // (If the package file already exists, FileMode.Create will
    //  automatically delete it first before creating a new one.
    using (Package package =
        Package.Open(packagePath, FileMode.Create))
    {
        // Add the Document part to the Package
        PackagePart packagePartDocument =
            package.CreatePart(partUriDocument,
                           System.Net.Mime.MediaTypeNames.Text.Xml);

        // Copy the data to the Document Part
        using (FileStream fileStream = new FileStream(
               documentPath, FileMode.Open, FileAccess.Read))
        {
            CopyStream(fileStream, packagePartDocument.GetStream());
        }

        // Add a Package Relationship to the Document Part
        package.CreateRelationship(packagePartDocument.Uri,
                                   TargetMode.Internal,
                                   PackageRelationshipType);

        // Add a Resource Part to the Package
        PackagePart packagePartResource =
            package.CreatePart(partUriResource,
                           System.Net.Mime.MediaTypeNames.Image.Jpeg);

        // Copy the data to the Resource Part
        using (FileStream fileStream = new FileStream(
               resourcePath, FileMode.Open, FileAccess.Read))
        {
            CopyStream(fileStream, packagePartResource.GetStream());
        }

        // Add Relationship from the Document part to the Resource part
        packagePartDocument.CreateRelationship(
                                new Uri(@"../resources/image1.jpg",
                                UriKind.Relative),
                                TargetMode.Internal,
                                ResourceRelationshipType);

    }

}


//  --------------------------- CopyStream ---------------------------
/// <summary>
///   Copies data from a source stream to a target stream.</summary>
/// <param name="source">
///   The source stream to copy from.</param>
/// <param name="target">
///   The destination stream to copy to.</param>
private static void CopyStream(Stream source, Stream target)
{
    const int bufSize = 0x1000;
    byte[] buf = new byte[bufSize];
    int bytesRead = 0;
    while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
        target.Write(buf, 0, bytesRead);
} --------------------编程问答-------------------- 这篇文章里介绍了如何解压,你看看能不能参照着写成压缩的代码:

C# Use Zip Archives without External Libraries
http://www.codeproject.com/Articles/209731/Csharp-use-Zip-archives-without-external-libraries

下面的来自上面文章:
To access simple Zip archives with ZipPackage fails because the content is checked for Package conventions.

For example, there has to be a file [Content_Types].xml in the root and only files with specified extensions are accessible. Filenames with special characters and spaces are not allowed and the access time is not the best because of the additional Package link logic.

However, the assembly WindowsBase.DLL is preinstalled and the generic Zip implementation is inside. The only problem is that the generic Zip classes are not public and visible for the programmers. But there is a simple way to get access to this hidden API and I wrote a small wrapper class for this. --------------------编程问答-------------------- 那你只能 反编译   ICSharpCode.SharpZipLib

然后自己创建 类了

--------------------编程问答--------------------
引用 2 楼 trigger_lau 的回复:
这个是需要用那个第三方组件,我想直接用。net自身的。

用J#调用java的zip相关内容,还可以添加crc232校验呢,.net自身的好像没有校验这块的 --------------------编程问答-------------------- 高手啊 --------------------编程问答-------------------- 版主说的那个相当好用,而且是开源的,为什么不用? --------------------编程问答-------------------- 用LS说的第三方开源库就可以(兼容NET2.0)
如果是Net3.0以上平台,可以引用WindowsBase.dll
using System.IO.Packaging;
LZ可以搜索一下
补充:.NET技术 ,  VB.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,