Cannot create ZipArchive in F#

Max*_*Max 5 compression zip f# unzip

I am trying to instantiate a ZipArchive class in System.IO.Compression in an F# project:

open System.IO
open System.IO.Compression
open System.IO.Compression.FileSystem //this line errors, as expected

// Define your library scripting code here

let directoryPath = @"C:\Users\max\Downloads"

let dirInfo = new DirectoryInfo(directoryPath)

let zippedFiles = dirInfo.GetFiles() 
|> Array.filter (fun x -> x.Extension.Equals(".zip"))

let fileStream = new FileStream(((Array.head zippedFiles).FullName), System.IO.FileMode.Open)

//this line does not compile, because ZipArchive is not defined
let archive = new System.IO.Compression.ZipArchive(fileStream)
Run Code Online (Sandbox Code Playgroud)

I can create the same thing in C# in the correct namespace:

var unzipper = new System.IO.Compression.ZipArchive(null);
Run Code Online (Sandbox Code Playgroud)

(This gives a bunch of errors because I'm passing null, but at least I can try to access it).

System.IO.Compression.FileSystem我的F#项目(父命名空间参考和,System.IO.Compression但在加载时.FileSystem的命名空间,我得到一个错误说“的命名空间的‘文件系统’没有定义”。

编辑

添加了我正在尝试执行的完整脚本文件,该文件重现了该问题。

open语句所示,我的项目引用了这两个库:

System.IO.Compression System.IO.Compression.FileSystem

我正在运行:

  • F# 4.4
  • .NET 4.6.1
  • 视觉工作室 2015
  • 视窗 10 64 位

编辑 2:修复!

我是在一个 F# 脚本文件中完成所有这些操作的.fsx,它需要告诉交互式环境像这样加载 DLL:

#if INTERACTIVE
#r "System.IO.Compression.dll"
#r "System.IO.Compression.FileSystem.dll"
#endif
Run Code Online (Sandbox Code Playgroud)

s95*_*163 4

您可以使用System.IO.Compression.NET 4.5 来操作 zip 文件。有关一些使用示例,请参阅相关文档

您可以将 FileStream 包装到 中ZipArchive,然后进一步操作它。扩展ExtractToDirectory方法非常方便。您可以创建一个 FileStream,实例化 ZipArchive,然后进一步操作它,例如通过使用CreateEntryFromFile扩展方法,理想情况下您应该尝试使用use一次性的,如writeZipFile示例中所示。

下面是读取和写入 zip 文件的示例:

#if INTERACTIVE
#r "System.IO.Compression.dll"
#r "System.IO.Compression.FileSystem.dll"
#endif

open System.IO
open System.IO.Compression

let zipfile = @"c:\tmp\test.zip"
File.Exists zipfile //true

let readZipFile (x:string) = 
    let x = new FileStream(x,FileMode.Open,FileAccess.Read)
    new ZipArchive(x)

let z = readZipFile zipfile
z.ExtractToDirectory(@"c:\tmp\test")
File.Exists @"c:\tmp\test\test.txt" // true

let writeZipFile (x:string) =
    use newFile = new FileStream(@"c:\tmp\newzip.zip",FileMode.Create)
    use newZip =  new ZipArchive(newFile,ZipArchiveMode.Create)
    newZip.CreateEntryFromFile(@"c:\tmp\test.txt","test.txt")

writeZipFile @"c:\tmp\test.txt"
File.Exists @"c:\tmp\newzip.zip"  // true
Run Code Online (Sandbox Code Playgroud)