gpt4 book ai didi

f# - 使用 System.IO.Compression.ZipArchive 进行压缩在 F# 代码中不起作用

转载 作者:行者123 更新时间:2023-12-05 00:13:09 25 4
gpt4 key购买 nike

我正在尝试使用以下脚本从 F# 中的字节数组创建一个 zip 文件。文件似乎已正确创建,但是当我尝试打开它时出现错误。

当我试图解压缩来自 zipFile 的字节数组时函数我得到了 System.IO.InvalidDataException: End of Central Directory record could not be found.
我在 zipFile 中做错了吗?功能?

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

open System.IO
open System.IO.Compression
open System.Linq

let zipFile (fileName: string) (data: byte []) =
try
use ms = new MemoryStream()
use archive = new ZipArchive(ms, ZipArchiveMode.Create)

let entry = archive.CreateEntry(fileName)
use entryStream = entry.Open()
use bw = new BinaryWriter(entryStream)
bw.Write(data)

Ok (ms.ToArray())
with e ->
Error <| sprintf "Cannot zip stream %s: %s" fileName e.Message

let saveFile path fileName (data: byte []) =
try
use fs = File.Open(Path.Combine(path, fileName + ".zip"), FileMode.OpenOrCreate)
fs.Write(data, 0, data.Length)
Ok ()
with e ->
Error <| sprintf "Cannot save file %s: %s" fileName e.Message

let data = "test" |> System.Text.Encoding.UTF8.GetBytes
let filename = "data.txt"

data
|> zipFile filename
|> Result.bind (saveFile "C:\\temp" filename)
|> printfn "%A"

最佳答案

您需要更细粒度地控制各种 IDisposable所涉及的资源已关闭,因此 ZipArchive的内容完全刷新到 MemoryStream在返回字节数组之前:

let zipFile (fileName: string) (data: byte []) =
try
use ms = new MemoryStream()
(
use archive = new ZipArchive(ms, ZipArchiveMode.Create)
let entry = archive.CreateEntry(fileName)
use entryStream = entry.Open()
use bw = new BinaryWriter(entryStream)
bw.Write(data)
)
Ok (ms.ToArray())
with e ->
Error <| sprintf "Cannot zip stream %s: %s" fileName e.Message

您可以使用 (...)use 添加显式/嵌套范围的括号绑定(bind)。

关于f# - 使用 System.IO.Compression.ZipArchive 进行压缩在 F# 代码中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48949380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com