Wednesday, May 13, 2009

C# - GZipStream to Zip and UnZip with Base64 Encoding

First of all, you can find sample code about Encoding and Decoding based on Base64 in the following link:

C# - UTF8/Base64 Encoder/Decoder
http://iborn2code.blogspot.com/search?q=Base64

class fbBase64
{
public static string EncodeToBase64(string theString)
{
return Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(theString));
}

public static string DecodeBase64(string theString)
{
return System.Text.Encoding.UTF8.GetString(
Convert.FromBase64String(theString));
}
}



public static bool GetZipBase64( string str2Zip, out byte[] aryBase64Zip )
{
bool retVal = true;
aryBase64Zip = null;

try
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzs = new GZipStream(ms, CompressionMode.Compress))
{
using (StreamWriter sw = new StreamWriter(gzs))
{
sw.Write(fbBase64.EncodeToBase64(str2Zip));
}
}
aryBase64Zip = ms.ToArray();
}
}
catch (Exception ex)
{
retVal = false;
MessageBox.Show(ex.ToString());
}
return retVal;
}



public static bool GetUnZipUnBase64( byte[] zipData, out string strOrgnl)
{
bool retVal = true;
strOrgnl = null;

try
{
using (MemoryStream ms = new MemoryStream(zipData) )
{
using (GZipStream gzs = new GZipStream(ms, CompressionMode.Decompress))
{
using ( StreamReader sr = new StreamReader(gzs) )
{
strOrgnl = fbBase64.DecodeBase64( sr.ReadToEnd() );
}
}
}
}
catch (Exception ex)
{
retVal = false;
MessageBox.Show(ex.ToString());
}
return retVal;
}

Share/Bookmark