vb.net - 如何在 vb.net 2005 中压缩文件

标签 vb.net file zip

如何在vb.net 2005中压缩文件(任何文件或文件夹)?

最佳答案

DotNetZip是一个易于使用、免费、开源的库,用于处理 VB.NET 和其他 .NET 语言的 ZIP 文件。

一些示例 VB.NET 代码,用于创建 zip 文件,一次添加一个文件:

Dim ZipToCreate As String = "ex1.zip"
Dim DirectoryToZip As String = "c:\temp"
Using zip As ZipFile = New ZipFile
    Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
    Dim filename As String
    For Each filename In filenames
        zip.AddFile(filename)
    Next
    zip.Save(ZipToCreate)
End Using

或者,将文件添加到组中:

Dim ZipToCreate As String = "ex1.zip"
Dim DirectoryToZip As String = "c:\temp"
Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
Using zip As ZipFile = New ZipFile
    zip.AddFiles(filenames, "temp")
    zip.Save(ZipToCreate)
End Using

或者,压缩整个目录或文件夹的代码:

Using zip As ZipFile = New ZipFile
    zip.AddDirectory(directory)
    zip.Save(targetZip)
End Using

提取 zip 文件的代码:

    Dim ZipFileToExtract As String = "c:\foo.zip"
    Using zip As ZipFile = ZipFile.Read(ZipFileToExtract)
        Dim e As ZipEntry
        For Each e In zip
            ' can conditionally extract here, '
            ' based on name, size, date, whatever.'
            e.Extract
        Next
    End Using

使用进度条提取:

Imports Ionic.Zip

Module SimpleUnzip
  Public Sub Unzip(ByVal ZipToUnpack As String, ByVal ExtractDirectory As String)
    Try
      Using zip As ZipFile = ZipFile.Read(ZipToUnpack)
        Form1.ProgressBar1.Maximum = zip.Entries.Count
        Dim entry As ZipEntry
        For Each entry In zip
            Form1.Label1.Text = entry.FileName
            entry.Extract(ExtractDirectory, ExtractExistingFileAction.OverwriteSilently)
            Form1.ProgressBar1.Value = Form1.ProgressBar1.Value + 1
            ' sleep because it's too fast otherwise.
            System.Threading.Thread.Sleep(50)
        Next
        Form1.ProgressBar1.Value = 0
        Form1.Label1.Text = "Done"
      End Using
    Catch ex1 As Exception
      Form1.Label1.Text = ("Exception: " & ex1.ToString())
    End Try
  End Sub
End Module

DotNetZip 具有用于读取、保存或提取的进度事件,因此您可以在 ASP.NET 或 Windows 窗体中支持进度条。它可以保护密码保护的 zip 文件、Unicode、ZIP64 和自解压存档。它生成的 zip 文件与所有其他 zip 工具兼容 - WinZip、WinRAR、Windows Explorer、Pkunzip 等。有一个很好的帮助文件 ( online version here ),其中包含大量代码示例。有samples available for download , 也。

关于vb.net - 如何在 vb.net 2005 中压缩文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/906354/

相关文章:

java - 在java中将文件作为附件发送

java - 如何用Java在大型机上解压PKZIP压缩文件?

bash - 需要在unix中压缩一定大小的单个文件并删除原始文件

javascript - fs.readFileSync 始终返回空字符串

java - Ant : jar and zipfileset - copy files from one JAR into another

.net - 私有(private)嵌套类

c# - 如何创建表达式树以执行与 "StartsWith"相同的操作

vb.net - C Type(str,DateTime) 和 DateTime.Parse(string) 之间的区别

vb.net - LINQ 中的 Equals 和 = 有什么区别?

c# - 我怎样才能用 .txt 文件填充我的组合框,但只有他们的名字没有路径?