簡體   English   中英

如何使用等效於VbScript的VB.NET代碼編寫文件以將文件添加到zip存檔中?

[英]How to write to add files to a zip archive using VB.NET code equivalent to VbScript?

以下vbscript代碼將文件夾的內容添加到zip存檔中:

Set objArgs = WScript.Arguments
folder = objArgs(0)
zip = objArgs(1)

CreateObject("Scripting.FileSystemObject").CreateTextFile(zip, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)

Set objShell = CreateObject("Shell.Application")
Set source = objShell.NameSpace(folder).Items
objShell.NameSpace(zip).CopyHere(source)

wScript.Sleep 5000

但是,當我嘗試使用等效的VB.NET代碼時,總是會得到一個空的zip文檔。 以下代碼做錯了什么?

Const folder As String = "C:\temp"
Const zip As String = "C:\output.zip"

CreateObject("Scripting.FileSystemObject").CreateTextFile(zip, True).Write("PK" & Chr(5) & Chr(6) & New String(Chr(65), 18).Replace(Chr(65), Chr(0))) 'New String(vbNullChar, 18))

Dim objShell As Object = CreateObject("Shell.Application")
Dim source As Object = objShell.NameSpace(folder).Items
objShell.NameSpace(zip).CopyHere(source)

Sleep(5000)

...聲明子睡眠庫“ kernel32”別名“睡眠”(ByVal dwMilliseconds作為整數)

在(vb).Net中,有一個非常好的用於編寫zip文件的庫。 http://dotnetzip.codeplex.com/

Dim z As New Ionic.Zip.ZipFile("File name of zip file")
z.AddDirectory("Path to directory to add")
z.save()

如果您正在使用(.NET 2)或(.NET 4),請嘗試(GZipStream): http : //msdn.microsoft.com/zh-cn/library/system.io.compression.gzipstream%28v=vs.80 %29.aspx

如果您正在使用(.NET 4.5),則使用(ZipArchive): http : //msdn.microsoft.com/zh-cn/library/system.io.compression.ziparchive%28v=vs.110%29.aspx

流暢的代碼對我有用

這是原始URL http://www.codeproject.com/Tips/257193/Easily-Zip-Unzip-Files-using-Windows-Shell

碼:

Dim outputZip As String = "output zip file path"
Dim inputZip As String = "input zip file path"
Dim inputFolder As String = "input folder path"
Dim outputFolder As String = "output folder path"

'Declare the shell object
Dim shObj As Object = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"))

Sub Zip()

    'Lets create an empty Zip File .
    'The following data represents an empty zip file.
    Dim startBytes() As Byte = {80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, _
                                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    'Data for an empty zip file.

    FileIO.FileSystem.WriteAllBytes(outputZip, startBytes, False)
    'We have successfully created the empty zip file.

    'Declare the folder which contains the items (files/folders) that you want to zip.
    Dim input As Object = shObj.NameSpace((inputFolder))

    'Declare the created empty zip file.
    Dim output As Object = shObj.NameSpace((outputZip))

    'Compress the items into the zip file.
    output.CopyHere((input.Items), 4)

End Sub

問候

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM