首页 > 解决方案 > 使用 Powershell 对大型 Zip 文件进行 Base64 编码

问题描述

我正在尝试将 ~66MB zip 文件 base64 编码为字符串并使用 Powershell 将其写入文件。我正在处理一个限制,最终我必须将 base64 编码的文件字符串直接包含到 Powershell 脚本中,这样当脚本在不同的位置运行时,可以从中重新创建 zip 文件。我不限于使用 Powershell 创建 base64 编码的字符串。这只是我最熟悉的。

我目前正在使用的代码:

$file = 'C:\zipfile.zip'
$filebytes = Get-Content $file -Encoding byte
$fileBytesBase64 = [System.Convert]::ToBase64String($filebytes)
$fileBytesBase64 | Out-File 'C:\base64encodedString.txt'

以前,我使用的文件足够小,编码速度相对较快。但是,我现在发现我正在编码的文件会导致进程耗尽我的所有 RAM,并且最终速度慢得令人难以置信。我觉得有更好的方法可以做到这一点,并会感谢任何建议。

标签: c#powershelltobase64string

解决方案


在我的情况下,编码或解码 117-Mb 文件只需不到 1 秒的时间。

Src file size: 117.22 MiB
Tgt file size: 156.3 MiB
Decoded size: 117.22 MiB
Encoding time: 0.294
Decoding time: 0.708

代码 I 制定措施:

$pathSrc = 'D:\blend5\scena31.blend'
$pathTgt = 'D:\blend5\scena31.blend.b64'
$encoding = [System.Text.Encoding]::ASCII

$bytes = [System.IO.File]::ReadAllBytes($pathSrc)
Write-Host "Src file size: $([Math]::Round($bytes.Count / 1Mb,2)) MiB"
$swEncode = [System.Diagnostics.Stopwatch]::StartNew()
$B64String = [System.Convert]::ToBase64String($bytes, [System.Base64FormattingOptions]::None)
$swEncode.Stop()
[System.IO.File]::WriteAllText($pathTgt, $B64String, $encoding)

$B64String = [System.IO.File]::ReadAllText($pathTgt, $encoding)
Write-Host "Tgt file size: $([Math]::Round($B64String.Length / 1Mb,2)) MiB"
$swDecode = [System.Diagnostics.Stopwatch]::StartNew()
$bytes = [System.Convert]::FromBase64String($B64String)
$swDecode.Stop()
Write-Host "Decoded size: $([Math]::Round($bytes.Count / 1Mb,2)) MiB"

Write-Host "Encoding time: $([Math]::Round($swEncode.Elapsed.TotalSeconds,3)) s"
Write-Host "Decoding time: $([Math]::Round($swDecode.Elapsed.TotalSeconds,3)) s"

推荐阅读