gpt4 book ai didi

c# - 将文件转换为 Base64String 并再次转换回来

转载 作者:IT王子 更新时间:2023-10-29 03:37:38 26 4
gpt4 key购买 nike

标题说明了一切:

  1. 我在 tar.gz 文件中读到过这样的内容
  2. 将文件分解为字节数组
  3. 将这些字节转换为 Base64 字符串
  4. 将该 Base64 字符串转换回字节数组
  5. 将这些字节写回一个新的 tar.gz 文件

我可以确认两个文件的大小相同(下面的方法返回 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);
}

编辑:工作示例要简单得多(感谢@T.S.):

Boolean MyMethod(){
byte[] AsBytes = File.ReadAllBytes(@"C:\...\file.tar.gz");
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);
}

谢谢!

最佳答案

如果您出于某种原因想要将文件转换为 base-64 字符串。比如如果你想通过互联网传递它,等等......你可以这样做

Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);

相应地,读回文件:

Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);

关于c# - 将文件转换为 Base64String 并再次转换回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25919387/

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