Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c# - Converting file into Base64String and back again

The title says it all:

  1. I read in a tar.gz archive like so
  2. break the file into an array of bytes
  3. Convert those bytes into a Base64 string
  4. Convert that Base64 string back into an array of bytes
  5. Write those bytes back into a new tar.gz file

I can confirm that both files are the same size (the below method returns true) but I can no longer extract the copy version.

Am I missing something?

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);
}

EDIT: 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);
}

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...