169

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!

abatishchev
  • 98,240
  • 88
  • 296
  • 433
darkpbj
  • 2,892
  • 4
  • 22
  • 32
  • You can't just change the the content of a compressed file like that. You'll have to decompress the file in step 1 instead of just read it in directly as is. And then step 5 will likewise have to be recompressing the data instead of just writing out the bytes directly. – itsme86 Sep 18 '14 at 18:10
  • 1
    Fortunately, as there was no actual manipulation of the file itself (basically just moving it from point A to B) this particular task doesn't require any (de/)compression – darkpbj Sep 18 '14 at 18:29

4 Answers4

416

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);
T.S.
  • 18,195
  • 11
  • 58
  • 78
  • 1
    Thankyou for the information, I tried going along with the answer below, but it didnt help, but this seemed to solve my problem with a simple openFileDialog – Mister SirCode Aug 02 '19 at 16:08
  • What if ToBase64String returns System.OutOfMemoryException? How do you optimize for large files and limited memory – Olorunfemi Davis Sep 05 '19 at 13:21
  • @OlorunfemiAjibulu then I suspect, you would need to use streams. Or break string into parts. One time I wrote custom encryption for large files where we saved encrypted chunks. We added 4 bytes to save integer value for chunk size. This way we knew to read so many positions – T.S. Sep 05 '19 at 14:21
  • Interesting @TaylorSpark. I used streams and I was fine. – Olorunfemi Davis Sep 06 '19 at 17:54
0

Another working example in VB.NET:

Public Function base64Encode(ByVal myDataToEncode As String) As String
    Try
        Dim myEncodeData_byte As Byte() = New Byte(myDataToEncode.Length - 1) {}
        myEncodeData_byte = System.Text.Encoding.UTF8.GetBytes(myDataToEncode)
        Dim myEncodedData As String = Convert.ToBase64String(myEncodeData_byte)
        Return myEncodedData
    Catch ex As Exception
        Throw (New Exception("Error in base64Encode" & ex.Message))
    End Try
    '
End Function
-1
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;  
}
Steve
  • 2,988
  • 2
  • 30
  • 47
hitesh kumar
  • 69
  • 1
  • 1
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read this [how-to-answer](http://stackoverflow.com/help/how-to-answer) for providing quality answer. – thewaywewere Jun 17 '17 at 11:19
  • 4
    why, again, do we need `java` if OP uses `c#`? – T.S. Sep 07 '17 at 19:05
  • 4
    @T.S. why, again, do we need java ? – Click Ok Jun 10 '18 at 14:14
-4

For Java, consider using Apache Commons FileUtils:

/**
 * Convert a file to base64 string representation
 */
public String fileToBase64(File file) throws IOException {
    final byte[] bytes = FileUtils.readFileToByteArray(file);
    return Base64.getEncoder().encodeToString(bytes);
}

/**
 * Convert base64 string representation to a file
 */
public void base64ToFile(String base64String, String filePath) throws IOException {
    byte[] bytes = Base64.getDecoder().decode(base64String);
    FileUtils.writeByteArrayToFile(new File(filePath), bytes);
}