Base64 decoding with FromBase64Transform

the example from MSDN seems to be reading the entire file in memory. I do not want it. The file should be processed block by block. So I tried to rewrite the example:

using (FromBase64Transform myTransform = new FromBase64Transform (FromBase64TransformMode.IgnoreWhiteSpaces)) { byte[] transformBuffer = new byte[myTransform.OutputBlockSize]; using (FileStream inputFile = File.OpenRead("/path/to/file/47311.b64")) { using(FileStream outputFile = File.OpenWrite("/path/to/file/47311.jpg")){ int bytesRead; byte[] inputBuffer = new byte[4096]; while ((bytesRead = inputFile.Read (inputBuffer, 0, 4096)) > 0) { int bytesWritten = myTransform.TransformBlock (inputBuffer, 0, 4, transformBuffer, 0); outputFile.Write (transformBuffer, 0, bytesWritten); } myTransform.Clear (); } } } 

But the image cannot be opened. What am I doing wrong?

+2
source share
2 answers

I believe this line is an error:

 int bytesWritten = myTransform.TransformBlock (inputBuffer, 0, 4, transformBuffer, 0); 

You convert 4 bytes, no matter how many bytes you read. I suspect you want:

 int bytesWritten = myTransform.TransformBlock (inputBuffer, 0, bytesRead, transformBuffer, 0); 

You may need to resize the transformBuffer , though - if you read up to 4K base64 data per iteration, you need up to 3K for plain text data per iteration.

A simpler option would probably be to create a CryptoStream using conversion, reading from the input stream, and then using Stream.CopyTo to write to FileStream .

+2
source

Now I tried CryptoStream , as John said:

 using (FileStream inputFile = File.OpenRead ("/your/path/file.b64")) using (FileStream outputFile = File.OpenWrite("/your/path/test.jpg")) using (FromBase64Transform myTransform = new FromBase64Transform (FromBase64TransformMode.IgnoreWhiteSpaces)) using (CryptoStream cryptoStream = new CryptoStream(inputFile, myTransform, CryptoStreamMode.Read)) { cryptoStream.CopyTo (outputFile, 4096); } 

It works and it is easier.

+1
source

Source: https://habr.com/ru/post/1235023/


All Articles