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

发布于 2024-07-25 06:42:49 字数 1539 浏览 5 评论 0原文

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

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

发布评论

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

评论(11

空‖城人不在 2024-08-01 06:42:50

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

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

红衣飘飘貌似仙 2024-08-01 06:42:50

如果您不想使用外部组件,这里是我昨晚使用 .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);
    }
} 

需要注意的事项:

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

  • 我尚未测试 CopyStream 方法以确保其行为正确,因为我最初是使用 Stream.CopyTo() 方法为 .NET 4.0 开发此方法。

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

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.aspx There 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.

极度宠爱 2024-08-01 06:42:50
    #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
    #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
余生一个溪 2024-08-01 06:42:50

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

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

南巷近海 2024-08-01 06:42:50

SevenZipSharp 是 7z.dll 和 LZMA SDK 的包装,它是开源且免费的。

SevenZipCompressor compressor = new SevenZipCompressor(); 
compressor.CompressionLevel = CompressionLevel.Ultra;
compressor.CompressionMethod = CompressionMethod.Lzma;
compressor.CompressionMode = CompressionMode.Create;
compressor.CompressFiles(...);

SevenZipSharp is a wrapper around tha 7z.dll and LZMA SDK, which is Open-source, and free.

SevenZipCompressor compressor = new SevenZipCompressor(); 
compressor.CompressionLevel = CompressionLevel.Ultra;
compressor.CompressionMethod = CompressionMethod.Lzma;
compressor.CompressionMode = CompressionMode.Create;
compressor.CompressFiles(...);
终难愈 2024-08-01 06:42:49

GPL

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

或以下限制性 Ms-PL

http://www.codeplex.com/DotNetZip

要完成此答案,.net框架有 ZipPackage 我的成功率较低它。

The GPL

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

OR the less restrictive Ms-PL

http://www.codeplex.com/DotNetZip

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

倾城月光淡如水﹏ 2024-08-01 06:42:49

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

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

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

destinationFolder.CopyHere(compressedFolderContents);

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

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 dynamic from Framework 4.0 in this example, but you can achieve the same results using 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_FLAGS to control behaviour of the CopyHere method.

季末如歌 2024-08-01 06:42:49

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

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

如果您有更复杂的需求,例如您想要选择要提取的条目,或者是否有密码,或者如果您想控制提取的文件的路径名,等等,那么这里有很多选择。 查看帮助文件以获取更多示例。

DotNetZip 是免费且开源的。

DotNetZip is easy to use. Here's an unzip sample

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 file for more examples.

DotNetZip is free and open source.

莫多说 2024-08-01 06:42:49

过去,我使用过 DotNetZip (MS-PL)、SharpZipLib (GPL) 和 适用于 C# 的 7ZIP SDK(公共领域)。 它们都工作得很好,而且都是开源的。

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

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

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.

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

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
  foreach (ZipEntry e in zip)
  {
    e.Extract(TargetDirectory);
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文