有没有一种简单的方法或方法可以将其Stream转换为byte[]C#?
标题说明了一切:
我可以确认这两个文件大小相同(以下方法返回true)但我无法再提取副本版本.
我错过了什么吗?
Boolean MyMethod(){
using (StreamReader sr = new StreamReader("C:\...\file.tar.gz")) {
String AsString = sr.ReadToEnd();
byte[] AsBytes = new byte[AsString.Length];
Buffer.BlockCopy(AsString.ToCharArray(), 0, AsBytes, 0, AsBytes.Length);
String AsBase64String = Convert.ToBase64String(AsBytes);
byte[] tempBytes = Convert.FromBase64String(AsBase64String);
File.WriteAllBytes(@"C:\...\file_copy.tar.gz", tempBytes);
}
FileInfo orig = new FileInfo("C:\...\file.tar.gz");
FileInfo copy = new FileInfo("C:\...\file_copy.tar.gz");
// Confirm that both original and copy file have the same number of bytes
return (orig.Length) == (copy.Length);
}
Run Code Online (Sandbox Code Playgroud)
编辑:工作示例更简单(感谢@TS):
Boolean MyMethod(){
byte[] AsBytes = File.ReadAllBytes(@"C:\...\file.tar.gz");
String AsBase64String …Run Code Online (Sandbox Code Playgroud) 如果我想生成Base64编码的输出,我将如何在.NET中执行此操作?
我知道从.NET 2.0开始,就有ICryptoTransform接口,以及该接口的 ToBase64Transform()和FromBase64Transform()实现.
但是这些类嵌入到System.Security命名空间中,并且需要使用TransformBlock,TransformFinalBlock等.
是否有更简单的方法在.NET中对base64进行数据流编码?
我在我的开发IIS服务器(来自VS2010 IDE)上运行以下方法,在64位Windows 7计算机上安装了16 GB的RAM:
public static MemoryStream copyStreamIntoMemoryStream(Stream stream)
{
long uiLen = stream.Length;
byte[] buff = new byte[0x8000];
int nSz;
MemoryStream ms = new MemoryStream();
try
{
while ((nSz = stream.Read(buff, 0, buff.Length)) != 0)
{
ms.Write(buff, 0, nSz);
}
}
finally
{
Debug.WriteLine("Alloc size=" + ms.Length);
}
return ms;
}
Run Code Online (Sandbox Code Playgroud)
我得到了System.OutOfMemoryException这一行:
ms.Write(buff, 0, nSz);
Run Code Online (Sandbox Code Playgroud)
分配268435456个字节时抛出:
Alloc size = 268435456
这是0x10000000或256 MB.所以我想知道是否需要设置一些全局设置才能使其正常工作?
以下是项目配置设置的屏幕截图:

我正在尝试将 ~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'
Run Code Online (Sandbox Code Playgroud)
以前,我使用的文件足够小,编码速度相对较快。然而,我现在发现我正在编码的文件会导致该过程耗尽我所有的 RAM,最终速度慢得难以忍受。我感觉有更好的方法可以做到这一点,并且非常感谢任何建议。
c# ×4
base64 ×2
.net ×1
asp.net ×1
bytearray ×1
inputstream ×1
memory ×1
powershell ×1
streamreader ×1