Convert file to Base64String and vice versa

The title says it all:

  • I read in tar.gz archive for example
  • split file into byte array
  • Convert these bytes to a Base64 string
  • Convert this Base64 string back to byte array
  • Write these bytes back to the new tar.gz file.

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

Did I miss 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 @TS):

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

Thank!

+67
c # base64 streamreader
Sep 18 '14 at
source share
2 answers

If you want to convert your file to base-64 string for some reason. For example, if you want to transfer it over the Internet, etc., you can do it

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

And accordingly, return to the file:

 Byte[] bytes = Convert.FromBase64String(b64Str); File.WriteAllBytes(path, bytes); 
+180
18 Sep '14 at 18:16
source share
 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; } 
+3
Jun 17 '17 at 10:57
source share



All Articles