Converting file into Base64String and back again(将文件转换为 Base64String 并再次返回)
问题描述
标题说明了一切:
- 我在 tar.gz 存档中读到这样的文件
- 将文件分解为字节数组
- 将这些字节转换为 Base64 字符串
- 将该 Base64 字符串转换回字节数组
- 将这些字节写回到新的 tar.gz 文件中
我可以确认两个文件的大小相同(以下方法返回 true),但我无法再提取副本版本.
I can confirm that both files are the same size (the below method returns true) but I can no longer extract the copy version.
我错过了什么吗?
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.):
The working example is much simpler (Thanks to @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 字符串.就像如果你想通过互联网传递它等等......你可以这样做
If you want for some reason to convert your file to base-64 string. Like if you want to pass it via internet, etc... you can do this
Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);
相应地,读回文件:
Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);
这篇关于将文件转换为 Base64String 并再次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将文件转换为 Base64String 并再次返回
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
