December 10th, 2008
Encoding and Decoding Binary data using Base64 with C# - 2
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!
It is often necessary to convert binary data to and from strings. One common way of encoding such information is through Base-64 encoding. The following post shows you how to convert a byte array to a Base64 string , and back again.
What is Base64?
Base-64 encoded information uses the most common characters: A-Z,a-z and 0-9, allowing for save storage of binary date in places that do not support binary.
The most common situation is e-mail, but it is also often used to encode binary data in XML files or other text file formats.
An example of Base-64 encoded data:
CRc6tbZ+170rwAQ5bPNYXvc8M7cx+xeJiyrFBpda
Implementing it in C#
The following example shows how to convert a byte array to a base-64 encoded string and back again. All the actual work is done by the System.Convert class. In the example below we use System.Security.Cryptography to fill our test array with random data.
using System;
using System.Security.Cryptography;
namespace Base64
{
class MainClass
{
public static bool VerifyEqual(byte[] one, byte[] two)
{
if (one.Length != two.Length) return false;
for (int Lp = 0; Lp < one.Length; Lp++)
if (!one[Lp].Equals(two[Lp])) return false;
return true;
}
public static void Main(string[] args)
{
byte[] DataToEncode = new byte[30];
// Fill the byte array with random data
RandomNumberGenerator Generator = RandomNumberGenerator.Create();
Generator.GetNonZeroBytes(DataToEncode);
// Convert the byte array to a base-64 string
string Base64String = Convert.ToBase64String(DataToEncode);
Console.WriteLine("{0}",Base64String);
// Convert the base-64 string back to a byte array
byte[] DecodedData = Convert.FromBase64String(Base64String);
// Verify that the data was decoded correctly
if (!VerifyEqual(DecodedData,DataToEncode))
Console.WriteLine("Byte[]'s do not match!");
else
Console.WriteLine("Byte[]'s match!");
}
}
}









Except where otherwise noted, content on this site is
February 2nd, 2009 at 12:04 am
Thank you for the code, this helped me complete and important project. I referenced you in my blog documentation.
Best regards, denglish
January 7th, 2011 at 12:29 pm
Wonderful!!!
Thanks for your help……