将文件转换为Base64String并再次返回

将文件转换为Base64String并再次返回

本文介绍了将文件转换为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并再次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 18:29