无法使用 System.IO.Compression.FileSystem.dll

Unable to use System.IO.Compression.FileSystem.dll

我正在尝试让这个 Powershell 代码工作:

     Add-Type -Path 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.IO.Compression.FileSystem.dll'
     $startPath = "D:\nade\CBA\Zip\StartPath"
     $zipPath = "D:\nade\CBA\Zip\result.zip"
     $extractPath = "D:\nade\CBA\Zip\Extract"
     [System.IO.Compression.FileSystem.ZipFile]::CreateFromDirectory($startPath, $zipPath)
     [System.IO.Compression.FileSystem.ZipFile]::ExtractToDirectory($zipPath, $extractPath)

但是我收到以下错误:

Unable to find type [System.IO.Compression.FileSystem.ZipFile]. Make sure that the assembly that contains this type is loaded.

我试过使用位于此处的其他 DLL:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\System.IO.Compression.FileSystem.dll

但是我仍然得到同样的错误。

如何正确导入这个库?

编辑:我已经尝试了以下所有方法,none 有效:

[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")
Add-Type -Path 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\System.IO.Compression.FileSystem.dll'
Add-Type -Path 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.IO.Compression.FileSystem.dll'
Add-type -AssemblyName "System.IO.Compression.FileSystem"

How to load assemblies in Powershell

一个过时的例子 LoadWithPartialName:

$sourceFolder = "c:\"
$destinationArc = "c:.zip" 
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourceFolder, $destinationArc)

Add-Type 的另一个示例(要加载程序集,请使用 -AssemblyName 参数):

Add-type -AssemblyName "System.IO.Compression.FileSystem";
$startPath = "c:\";
$zipPath = "c:.zip";
[System.IO.Compression.ZipFile]::CreateFromDirectory($startPath, $zipPath);

原来我使用的命名空间不正确。

ZipFile 位于 System.IO.Compression 命名空间中,而程序集称为 System.IO.Compression.FileSystem.dll.

即。它与加载程序集无关,我只需要使用正确的命名空间:

     [System.IO.Compression.ZipFile]::CreateFromDirectory($startPath, $zipPath)
     [System.IO.Compression.ZipFile]::ExtractToDirectory($zipPath, $extractPath)

我在 Win 2008 R2 服务器上遇到过这个问题。结果我需要更新到 PowerShell 3.0 版才能工作。当我尝试这个时,我终于想通了:

Add-Type -Path "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.IO.Compression.FileSystem.dll"

并收到有关版本不兼容的消息。

现在我的代码运行良好:

Add-Type -AssemblyName "System.IO.Compression.FileSystem"
[System.IO.Compression.ZipFile]::CreateFromDirectory("C:\Temp\lrressults", "C:\OutEmail\LoadRestReportzip") 

我 运行 遇到了类似的错误,无法让它工作 (Windows Server 2008R2)。安装 .NET 4.5 和 Powershell 3.0(如在某些论坛中找到的)后,它仍然无法工作。它仅在我添加 both 这些行后才起作用:

Add-Type -assembly "System.IO.Compression" Add-Type -assembly "System.IO.Compression.Filesystem"