将文件转换为 Base64String 并再次返回 [英] Converting file into Base64String and back again

查看:23
本文介绍了将文件转换为 Base64String 并再次返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说明了一切:

  1. 我在 tar.gz 存档中读到这样的文件
  2. 将文件分解为字节数组
  3. 将这些字节转换为 Base64 字符串
  4. 将该 Base64 字符串转换回字节数组
  5. 将这些字节写回到新的 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 并再次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆