关于c#:将文件转换为Base64String,然后再返回

Converting file into Base64String and back again

标题说明了一切:

  • 我在tar.gz档案里读到的,就像这样
  • 将文件拆分为字节数组
  • 将这些字节转换为base64字符串
  • 将base64字符串转换回字节数组
  • 将这些字节写回一个新的tar.gz文件
  • 我可以确认两个文件的大小相同(下面的方法返回true),但我不能再提取副本版本。

    我错过什么了吗?

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    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.):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    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字符串。比如如果你想通过互联网等方式传递信息…你可以做到这一点

    1
    2
    Byte[] bytes = File.ReadAllBytes("path");
    String file = Convert.ToBase64String(bytes);

    相应地,读回文件:

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    private String encodeFileToBase64Binary(File file){    
    String encodedfile = null;  
    try {  
        FileInputStream fileInputStreamReader = new FileInputStream(file);  
        byte[] bytes = new byte[(int)file.length()];
        fileInputStreamReader.read(bytes);  
        encodedfile = Base64.encodeBase64(bytes).toString();  
    } catch (FileNotFoundException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    } catch (IOException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }  
        return encodedfile;  
    }