C#转换文件到Base64String,然后再返回 [英] C# Converting file into Base64String and back again

查看:667
本文介绍了C#转换文件到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);

相应地,回读文件:

And correspondingly, read back to file:

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

这篇关于C#转换文件到Base64String,然后再返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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