Search code examples
c#file-uploadencodingfile-encodings

Converting a string rappresentation of a file (byte array) back to a file in C#


As in the title I'm trying to convert back a string rappresentation of a bytearray to the original file where the bytes where taken.

What I've done:

I've a web service that gets a whole file and sends it:

answer.FileByte = File.ReadAllBytes(@"C:\QRY.txt");

After the serialization in the transmitted result xml I've this line:

<a:FileByte>TVNIfGF8MjAxMzAxMDF8YQ1QSUR8YXxhfGF8YXxhfGF8YXwyMDEzMDEwMXxhfGF8YXxhfGF8YXxhfGF8YXxhfGF8YXxhDVBWMXxhfGF8YXxhfGF8YXxhfGF8YXxhfDIwMTMwMTAxfDIwMTMwMTAxfDB8MHxhDQo=</a:FileByte>

I've tried to convert it back with this line in another simple application:

//filepath is the path of the file created
//bytearray is the string from the xml (copypasted)
File.WriteAllBytes(filepath, Encoding.UTF8.GetBytes(bytearray));

I've used UTF8 as enconding since the xml declares to use this charset. Keeping the datatype is not an option since I'm writing a simple utility to check the file conversion.

Maybe I'm missing something very basic but I'm not able to come up with a working solution.


Solution

  • This certainly isn't UTF8, the serializer probably converted it to Base64.

    Use Convert.FromBase64String() to get your bytes back

    Assuming that bytearray is the "TVNIfGF8M..." string, try:

    string bytearray = ...;
    File.WriteAllBytes(filepath, Convert.FromBase64String(bytearray));