對於比較簡單的使用,如果你希望把拉鍊包含的所有文件現有的文件夾。
這很簡單,因爲您不必確保指定完整的文件名,它只需要在文件夾中找到所有文件。不過,您必須在「destination_file.zip」文件名上指定「.zip」擴展名。
正如在另一個答案中指出的,您需要添加兩個引用到您的項目。
- System.IO.Compression
- System.IO.Compression。FileSystem
並將這些Import語句添加到您的類文件中。
Imports System.IO
Imports System.IO.Compression
這裏是按鈕點擊程序中的一些代碼,它可以放在其他地方。正如你所看到的,它只是一行代碼。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ZipFile.CreateFromDirectory("Folder you want to zip",
"destination_file.zip",
CompressionLevel.Optimal,
False)
End Sub
但看起來你希望將選定的文件發送到.zip壓縮文件。
比方說,你有一個名爲dgv1 DataGridView控件,用數據填充的幾行,你有多種選擇其中的幾個線條,以及全路徑/文件名是在DataGridView的第一列。
有一個幫助函數(selectedList())將datagridview中的選定單元格式化爲完整路徑/文件名列表。
zipEm()函數獲取文件列表和目標存檔文件名並創建一個.zip文件。
Button1_Click()例程調用前兩個例程並向用戶提供反饋。
' returns list of items from column col that are selected
Function selectedList(dgv1 As DataGridView, col As Integer) As List(Of String)
selectedList = New List(Of String)
For Each cell As DataGridViewCell In dgv1.SelectedCells
If cell.ColumnIndex = col Then selectedList.Add(cell.Value.ToString())
Next
End Function
' archives a list of files to the designated file (overwriting, if it already exists)
Function zipEm(fileList As List(Of String), nzfName As String) As Boolean
Try
If File.Exists(nzfName) Then File.Delete(nzfName)
Using newZipFile As ZipArchive = ZipFile.Open(nzfName, ZipArchiveMode.Create)
For Each pfn As String In fileList
newZipFile.CreateEntryFromFile(pfn, Path.GetFileName(pfn))
Next
End Using
Catch ex As Exception
Return False
End Try
Return True
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fileList As List(Of String) = selectedList(dgv1, 0)
If fileList.Count = 0 Then
MsgBox("No valid items selected.", vbExclamation, "'lil problem")
Exit Sub
End If
Dim nzfName As String = Path.Combine(Path.GetDirectoryName(fileList(0)),
"sample (" & fileList.Count.ToString() & " items).zip")
If zipEm(fileList, nzfName) Then
MsgBox("Saved zip file containing " & fileList.Count.ToString() & " items.",
vbOKOnly, "sucess")
Else
MsgBox("Unable to save .zip file.", vbExclamation, "'lil problem")
End If
End Sub
如果你喜歡的文件累積到存檔(而不是覆蓋),常量「ZipArchiveMode.Create」可以在ZipFile.Open()調用的改爲「ZipArchiveMode.Update」 zipEm()例程。
'沒有第三方庫如dotnet'這不是第三方它是4.5框架的一部分。如果是這樣的話,那麼編寫你自己的壓縮算法,這將是一個開始... – Codexer
@Zaggler謝謝你的回覆!但從我閱讀的內容中我需要下載dotnetziplibrary來使用它?我嘗試編寫自己的算法,但是我很難理解如何在zip壓縮文件或壓縮文件中添加文件我只能找到如何創建一個條目並將其寫入或寫入現有文件 – jean55
因此,您希望「添加」到一個檔案***或***你想「創建」一個帶有文件的zip文件,哪一個? – Codexer