Converting a File to a Base64 Encoded String

May 8th, 2008
by psykoprogrammer

Sometimes it is necessary to send a file to someplace, but not practical to send it as a binary file. This is where base64 encoding comes in handy. Such a think has many uses, for example in webservices. It may be necessary to send a file via webservice to some 3rd party system. Base64 encoding allows you to overcome the firewall by converting that binary data to string data. Here’s an example of converting a file to Base64 encoding.

  1. private string ConvertFileToBase64(string Filename)
  2. {
  3.    string result = "";
  4.  
  5.    using (FileStream reader = new FileStream(Filename, FileMode.Open, FileAccess.Read))
  6.    {
  7.       byte[] buffer = new byte[reader.Length];
  8.       reader.Read(buffer, 0, (int) reader.Length);
  9.  
  10.       result = Convert.ToBase64String(buffer);
  11.    }
  12.  
  13.    return result;
  14. }

And there you have it! Send that puppy all over the internet!

Comments (1)

One Response to “Converting a File to a Base64 Encoded String”

  1. New Article: Encoding files as base64 strings » Adam->Blog(); Says:

    [...] out my new article on encoding files as base64 strings. Useful for sending binary data across the wire where sending such binary data [...]

Leave a Reply

You must be logged in to post a comment.