我想为我为 asp.net 网站创建的插件创建一个 zip 提取器。我希望客户端能够运行提取器,并将文件放入我指定的正确文件夹中。有什么工具可以做到这一点吗?我不知道该怎么做,谢谢
最佳答案
DotNetZip是一个允许托管代码应用程序读取或写入 zip 文件的库。它允许您做的一件事是生成自解压存档 (SFX)。
在 C# 中,使用 DotNetZip 生成 SFX 存档的代码如下所示:
using (ZipFile zip1 = new ZipFile())
{
// zip up a directory
zip1.AddDirectory("C:\\project1\\datafiles", "data");
zip1.Comment = "This will be embedded into a self-extracting exe";
zip1.AddEntry("Readme.txt", "This is content for a 'Readme' file that will appear in the zip.");
zip1.SaveSelfExtractor("archive.exe", SelfExtractorFlavor.WinFormsApplication);
}
您可以选择如何塑造 ZIP 文件中的文件夹层次结构。唯一的规则是,在提取时,提取发生在特定的根文件夹或父文件夹中。 (您不能提取到分散在文件系统中的 7 个不同目录)
生成的 EXE 需要 .NET Framework 2.0 或更高版本才能运行,但仅此而已。
SFX/EXE 也是一个常规 Zip 文件,您可以使用 WinZip 或其他 zip 工具(包括 Windows 资源管理器“压缩文件夹”)读取和提取它。
SFX 与其他 zip 功能组合在一起,包括
在 DotNetZip 中,您可以生成两种可能的 SFX 风格:控制台应用程序或 WinForms 应用程序。 WinForms UI 是为您生成的 - 无需编写或设计。它简单实用,看起来像这样:
控制台风格更适合在脚本或 headless (无 UI)场景中使用。
制作 SFX 时有很多选择,例如:
所有这些关于 SFX 行为方式的选项都可以通过 DotNetZip 类库接口(interface)访问。
如果您不喜欢内置 SFX 功能的 UI 或工作模型,有一种简单的方法可以提供您自己的自提取器 UI + 逻辑。例如,您可以在 WPF 中构建一个应用程序,并使其变得时髦且视觉上充满活力。它的工作方式非常简单:在生成 SFX 的代码中,将解压缩 stub EXE(WinForms、WPF 或其他)复制到输出流,然后在不关闭流的情况下将 Zip 文件保存到同一流.它在 VB 中看起来像这样:
Public Shared Function Main(ByVal args As String()) As Integer
Dim sfxStub As String = "my-sfx-stub.exe"
Dim outputFile As String = "my-sfx-archive.exe"
Dim directoryToZip As String = "c:\directory\to\ZIP"
Dim buffer As Byte() = New Byte(4000){}
Dim n As Integer = 1
Using output As System.IO.Stream = File.Open(outputFile, FileMode.Create)
'' copy the contents of the sfx stub to the output stream
Using input As System.IO.Stream = File.Open(sfxStub, FileMode.Open)
While n <> 0
n = input.Read(buffer, 0, buffer.Length)
If n <> 0 Then
output.Write(buffer, 0, n)
End If
End While
End Using
'' now save the zip file to the same stream
Using zp As New ZipFile
zp.AddFiles(Directory.GetFiles(directoryToZip), False, "")
zp.Save(output)
End Using
End Using
End Function
此代码创建的结果文件既是 EXE 文件,也是 ZIP 文件。 stub EXE 必须从自身读取才能提取。在上面的示例中,my-sfx-stub.exe 程序的代码可能很简单:
Dim a As Assembly = Assembly.GetExecutingAssembly
Try
'' read myself as a zip file
Using zip As ZipFile = ZipFile.Read(a.Location)
Dim entry As ZipEntry
For Each entry in zip
'' extract here, or add to a listBox, etc.
'' listBox1.Items.Add(entry.FileName)
Next
End Using
Catch
MessageBox.Show("-No embedded zip file.-")
End Try
以这种简单方式构建的自定义 SFX 将依赖于 DotNetZip DLL。为避免这种情况,并生成一个独立的 EXE,无需额外的 DLL 依赖即可提取,您可以使用 ILMerge,或 embed the DotNetZip DLL as a resource and use an AssemblyResolver event to load it来自嵌入式资源。
如有疑问,可以在the DotNetZip forums上提问.
关于.net - 创建一个 zip 提取器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1578823/