FOLLOW US
4dots Software CODE BLOG

How to Base64 Encode a String with custom encoding

To Base64 encode a string with custom encoding do the following :

	string text_to_encode="hello world";
	
	Encoding enc = Encoding.Default;            
	
	string base64str = System.Convert.ToBase64String(enc.GetBytes(text_to_encode), Base64FormattingOptions.None);
If you would like to format the generated text so that it includes line breaks, do the following :

	
	string text_to_encode="hello world";
	
	Encoding enc = Encoding.Default;            	
    
    string base64str  = System.Convert.ToBase64String(enc.GetBytes(text_to_encode), Base64FormattingOptions.InsertLineBreaks);    

You can change the enc Encoding with the encoding you want.

You can get an encoding from its codepage number with enc=Encoding.GetEncoding(codepage_number); e.g.


Encoding enc=Encoding.GetEncoding(65001);
 
for Unicode UTF-8 encoding.

Download Demo Project

Encode Decode Demo Project
 

Please Donate!

Please Share!