使用C#wpf压缩和解压缩文件

时间:2014-05-28 08:16:10

标签: c# wpf visual-studio-2010 unzip

我正在开发一个需要解压缩文件并存储在特定文件夹中的项目。但问题是,我不知道该怎么做。这是我第一次参与这类项目。

我正在使用visual studio 2010.而且我不会使用任何第三方应用程序。

有人可以建议我怎么做?

我尝试过这段代码,但ZIPFILE无法识别。它上面有一条红线。

using System;
using System.IO;
using System.IO.Compression;

namespace UnzipFile
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnZip_Click(object sender, RoutedEventArgs e)
    {
        string startPath = @"c:\example\start";
        string zipPath = @"c:\example\result.zip";
        string extractPath = @"c:\example\extract";

        ZipFile.CreateFromDirectory(startPath, zipPath);

        ZipFile.ExtractToDirectory(zipPath, extractPath);
    }
}

}

enter image description here

5 个答案:

答案 0 :(得分:7)

Microsoft已在.NET框架中使用ZipFile命名空间包含存档。

为了使其非常简短,要压缩目录,您可以使用以下代码:

ZipFile.CreateFromDirectory(sourceFolder, outputFile);

答案 1 :(得分:1)

I've use this code to solve my problem...

我也在我的参考文献

中做了这个

enter image description here

然后添加此代码。

public static void UnZip(string zipFile, string folderPath)
    {
        if (!File.Exists(zipFile))
            throw new FileNotFoundException();

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

        Shell32.Shell objShell = new Shell32.Shell();
        Shell32.Folder destinationFolder = objShell.NameSpace(folderPath);
        Shell32.Folder sourceFile = objShell.NameSpace(zipFile);

        foreach (var file in sourceFile.Items())
        {
            destinationFolder.CopyHere(file, 4 | 16);
        }
    }

并在按钮事件中

private void btnUnzip_Click(object sender, RoutedEventArgs e)
    {
        UnZip(@"E:\Libraries\Pictures\EWB FileDownloader.zip", @"E:\Libraries\Pictures\sample");
    }

我告诉你,它确实有用。

答案 2 :(得分:1)

System.IO.Compression.FileSystem.dll

下载上面的dll文件。 转到解决方案资源管理器 - &gt;右键单击References, 单击“添加引用”。 在窗口中选择“Windows” 选择“扩展” 选择“浏览” 并转到解压缩System.IO.Compression.FileSystem.dll文件的文件夹。

点击“确定” 并再次运行该应用程序。 : - )

答案 3 :(得分:0)

以下链接显示了两个用于压缩和解压缩到C#中文件的示例。您可以使用此示例。

样品(使用7-zip):

var tmp = new SevenZipCompressor();
tmp.ScanOnlyWritable = true;
tmp.CompressFilesEncrypted(outputFilePath, password, filePaths);

示例(使用ZipArchive):

ZipArchive zip = ZipFile.Open(filePath, ZipArchiveMode.Create);
zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
zip.Dispose();

了解更多信息:

http://csharpexamples.com/zip-and-unzip-files-programmatically-in-c/

答案 4 :(得分:0)

使用System.IO.Compression;

在您的代码中包含上述程序集。 它包含以下2种方法的定义

ZipFile.CreateFromDirectory(startPath,zipPath);  ZipFile.ExtractToDirectory(zipPath,extractPath);