推荐一个库/API 在 C# 中解压缩文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1023476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:44:58  来源:igfitidea点击:

recommend a library/API to unzip file in C#

c#.netzip

提问by George2

Looks like no built-in Library/API in C# to unzip a zip file. I am looking for a free (better open source) library/API which could work with .Net 3.5 + VSTS 2008 + C# to unzip a zip file and extract all files into a specific folder.

看起来 C# 中没有内置库/API 来解压缩 zip 文件。我正在寻找一个免费的(更好的开源)库/API,它可以与 .Net 3.5 + VSTS 2008 + C# 一起使用来解压一个 zip 文件并将所有文件解压到一个特定的文件夹中。

Any recommended library/API or samples?

任何推荐的库/API 或示例?

采纳答案by Sam Saffron

The GPL

通用公共许可证

http://www.icsharpcode.net/OpenSource/SharpZipLib/

http://www.icsharpcode.net/OpenSource/SharpZipLib/

OR the less restrictive Ms-PL

或限制较少的 Ms-PL

http://www.codeplex.com/DotNetZip

http://www.codeplex.com/DotNetZip

To complete this answer the .net framework has ZipPackageI had less success with it.

为了完成这个答案,.net 框架有ZipPackage我用它不太成功。

回答by C-Pound Guru

If you want to use 7-zip compression, check out Peter Bromberg's EggheadCafe article. Beware: the LZMA source codefor c# has no xml comments (actually, very few comments at all).

如果您想使用 7-zip 压缩,请查看 Peter Bromberg 的EggheadCafe 文章。注意:c#的LZMA 源代码没有 xml 注释(实际上,根本没有注释)。

回答by Cheeso

DotNetZipis easy to use. Here's an unzip sample

DotNetZip易于使用。这是一个解压示例

using (var zip = Ionic.Zip.ZipFile.Read("archive.zip"))
{
   zip.ExtractAll("unpack-directory");
}

If you have more complex needs, like you want to pick-and-choose which entries to extract, or if there are passwords, or if you want to control the pathnames of the extracted files, or etc etc etc, there are lots of options. Check the help filefor more examples.

如果你有更复杂的需求,比如你想选择提取哪些条目,或者如果有密码,或者如果你想控制提取文件的路径名,等等等等,有很多选项. 查看帮助文件以获取更多示例。

DotNetZip is free and open source.

DotNetZip 是免费和开源的。

回答by Maxim Zaslavsky

In the past, I've used DotNetZip(MS-PL), SharpZipLib(GPL), and the 7ZIP SDK for C#(public domain). They all work great, and are open source.

过去,我使用过DotNetZip(MS-PL)、SharpZipLib(GPL) 和7ZIP SDK for C#(公共领域)。它们都运行良好,并且是开源的。

I would choose DotNetZip in this situation, and here's some sample code from the C# Examples page:

在这种情况下,我会选择 DotNetZip,这里有一些来自C# 示例页面的示例代码:

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
  foreach (ZipEntry e in zip)
  {
    e.Extract(TargetDirectory);
  }
}

回答by Maxim Zaslavsky

Have a look to my small library: https://github.com/jaime-olivares/zipstorer

看看我的小图书馆:https: //github.com/jaime-olivares/zipstorer

回答by Martin Vobr

I would recommend our http://www.rebex.net/zip.net/but I'm biased. Downloadtrial and check the features and samples yourself.

我会推荐我们的http://www.rebex.net/zip.net/但我有偏见。下载试用版并自行检查功能和示例。

回答by Simon M?Kenzie

If all you want to do is unzip the contents of a file to a folder, and you know you'll only be running on Windows, you can use the Windows Shell object. I've used dynamicfrom Framework 4.0 in this example, but you can achieve the same results using Type.InvokeMember.

如果您只想将文件的内容解压缩到一个文件夹中,并且您知道您只能在 Windows 上运行,则可以使用 Windows Shell 对象。我dynamic在本示例中使用了 Framework 4.0,但您可以使用Type.InvokeMember.

dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));

dynamic compressedFolderContents = shellApplication.NameSpace(sourceFile).Items;
dynamic destinationFolder = shellApplication.NameSpace(destinationPath);

destinationFolder.CopyHere(compressedFolderContents);

You can use FILEOP_FLAGSto control behaviour of the CopyHeremethod.

您可以使用FILEOP_FLAGS来控制CopyHere方法的行为。

回答by Joshua

If you do not want to use an external component, here is some code I developed last night using .NET's ZipPackage class.

如果您不想使用外部组件,这里是我昨晚使用 .NET 的 ZipPackage 类开发的一些代码。

private static void Unzip()
{
    var zipFilePath = "c:\myfile.zip";
    var tempFolderPath = "c:\unzipped";

    using (Package pkg = ZipPackage.Open(zipFilePath, FileMode.Open, FileAccess.Read))
    {
        foreach (PackagePart part in pkg.GetParts())
        {
            var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/')));
            var targetDir = target.Remove(target.LastIndexOf('\'));

            if (!Directory.Exists(targetDir))
                Directory.CreateDirectory(targetDir);

            using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
            {
                CopyStream(source, File.OpenWrite(target));
            }
        }
    }
}

private static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[4096];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, read);
    }
} 

Things to note:

注意事项:

  • The ZIP archive MUST have a [Content_Types].xml file in its root. This was a non-issue for my requirements as I will control the zipping of any ZIP files that get extracted through this code. For more information on the [Content_Types].xml file, please refer to: http://msdn.microsoft.com/en-us/magazine/cc163372.aspxThere is an example file below Figure 13 of the article.

  • I have not tested the CopyStream method to ensure it behaves correctly, as I originally developed this for .NET 4.0 using the Stream.CopyTo() method.

  • ZIP 存档必须在其根目录中有一个 [Content_Types].xml 文件。这对我的要求来说不是问题,因为我将控制通过此代码提取的任何 ZIP 文件的压缩。有关[Content_Types].xml 文件的更多信息,请参阅:http: //msdn.microsoft.com/en-us/magazine/cc163372.aspx文章图 13 下方有一个示例文件。

  • 我没有测试 CopyStream 方法以确保它的行为正确,因为我最初是使用 Stream.CopyTo() 方法为 .NET 4.0 开发的。

回答by Asif

    #region CreateZipFile
    public void StartZip(string directory, string zipfile_path)
    {
        Label1.Text = "Please wait, taking backup";
            #region Taking files from root Folder
                string[] filenames = Directory.GetFiles(directory);

                // path which the zip file built in 
                ZipOutputStream p = new ZipOutputStream(File.Create(zipfile_path));
                foreach (string filename in filenames)
                {
                    FileStream fs = File.OpenRead(filename);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    ZipEntry entry = new ZipEntry(filename);
                    p.PutNextEntry(entry);
                    p.Write(buffer, 0 , buffer.Length);
                    fs.Close();
                }
            #endregion

            string dirName= string.Empty;
            #region Taking folders from root folder
                DirectoryInfo[] DI = new DirectoryInfo(directory).GetDirectories("*.*", SearchOption.AllDirectories);
                foreach (DirectoryInfo D1 in DI)
                {

                    // the directory you need to zip 
                    filenames = Directory.GetFiles(D1.FullName);
                    if (D1.ToString() == "backup")
                    {
                        filenames = null;
                        continue;
                    }
                    if (dirName == string.Empty)
                    {
                        if (D1.ToString() == "updates" || (D1.Parent).ToString() == "updates" || (D1.Parent).Parent.ToString() == "updates" || ((D1.Parent).Parent).Parent.ToString() == "updates" || (((D1.Parent).Parent).Parent).ToString() == "updates" || ((((D1.Parent).Parent).Parent)).ToString() == "updates")
                        {
                            dirName = D1.ToString();
                            filenames = null;
                            continue;
                        }
                    }
                    else
                    {
                        if (D1.ToString() == dirName) ;
                    }
                    foreach (string filename in filenames)
                    {
                        FileStream fs = File.OpenRead(filename);
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        ZipEntry entry = new ZipEntry(filename);
                        p.PutNextEntry(entry);
                        p.Write(buffer, 0, buffer.Length);
                        fs.Close();
                    }
                    filenames = null;
                }
                p.SetLevel(5);
                p.Finish();
                p.Close();
           #endregion
    }
    #endregion

    #region EXTRACT THE ZIP FILE
    public bool UnZipFile(string InputPathOfZipFile, string FileName)
    {
        bool ret = true;
        Label1.Text = "Please wait, extracting downloaded file";
        string zipDirectory = string.Empty;
        try
        {
            #region If Folder already exist Delete it
            if (Directory.Exists(Server.MapPath("~/updates/" + FileName))) // server data field
            {
                String[] files = Directory.GetFiles(Server.MapPath("~/updates/" + FileName));//server data field
                foreach (var file in files)
                    File.Delete(file);
                Directory.Delete(Server.MapPath("~/updates/" + FileName), true);//server data field
            }
            #endregion


            if (File.Exists(InputPathOfZipFile))
            {
                string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile);

                using (ZipInputStream ZipStream = new

                ZipInputStream(File.OpenRead(InputPathOfZipFile)))
                {
                    ZipEntry theEntry;
                    while ((theEntry = ZipStream.GetNextEntry()) != null)
                    {
                        if (theEntry.IsFile)
                        {
                            if (theEntry.Name != "")
                            {
                                string directoryName = theEntry.Name.Substring(theEntry.Name.IndexOf(FileName)); // server data field

                                string[] DirectorySplit = directoryName.Split('\');
                                for (int i = 0; i < DirectorySplit.Length - 1; i++)
                                {
                                    if (zipDirectory != null || zipDirectory != "")
                                        zipDirectory = zipDirectory + @"\" + DirectorySplit[i];
                                    else
                                        zipDirectory = zipDirectory + DirectorySplit[i];
                                }
                                string first = Server.MapPath("~/updates") + @"\" + zipDirectory;
                                if (!Directory.Exists(first))
                                    Directory.CreateDirectory(first);


                                string strNewFile = @"" + baseDirectory + @"\" + directoryName;


                                if (File.Exists(strNewFile))
                                {
                                    continue;
                                }
                                zipDirectory = string.Empty;

                                using (FileStream streamWriter = File.Create(strNewFile))
                                {
                                    int size = 2048;
                                    byte[] data = new byte[2048];
                                    while (true)
                                    {
                                        size = ZipStream.Read(data, 0, data.Length);
                                        if (size > 0)
                                            streamWriter.Write(data, 0, size);
                                        else
                                            break;
                                    }
                                    streamWriter.Close();
                                }
                            }
                        }
                        else if (theEntry.IsDirectory)
                        {
                            string strNewDirectory = @"" + baseDirectory + @"\" +

                            theEntry.Name;
                            if (!Directory.Exists(strNewDirectory))
                            {
                                Directory.CreateDirectory(strNewDirectory);
                            }
                        }
                    }
                    ZipStream.Close();
                }
            }
        }
        catch (Exception ex)
        {
            ret = false;
        }
        return ret;
    }  
    #endregion