【发布时间】:2014-11-13 04:34:42
【问题描述】:
标题说明了一切:
- 我在 tar.gz 存档中读到这样的文件
- 将文件分解为字节数组
- 将这些字节转换为 Base64 字符串
- 将该 Base64 字符串转换回字节数组
- 将这些字节写回到新的 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);
}
谢谢!
【问题讨论】:
-
你不能像那样改变压缩文件的内容。您必须在步骤 1 中解压缩文件,而不是直接按原样读入。然后第 5 步同样必须重新压缩数据,而不是直接写出字节。
-
幸运的是,由于没有对文件本身进行实际操作(基本上只是将其从 A 点移动到 B),因此此特定任务不需要任何 (de/) 压缩
标签: c# base64 streamreader system.io.fileinfo