CSharp examples for File IO:MemoryStream
Base64 Encode Binary Data
using System;/*from w w w .j a va 2s . com*/ using System.IO; using System.Text; class MainClass { public static byte[] DecimalToByteArray (decimal src) { // Create a MemoryStream as a buffer to hold the binary data. using (MemoryStream stream = new MemoryStream()) { // Create a BinaryWriter to write binary data the stream. using (BinaryWriter writer = new BinaryWriter(stream)) { // Write the decimal to the BinaryWriter/MemoryStream. writer.Write(src); // Return the byte representation of the decimal. return stream.ToArray(); } } } public static decimal ByteArrayToDecimal (byte[] src) { using (MemoryStream stream = new MemoryStream(src)) { using (BinaryReader reader = new BinaryReader(stream)) { return reader.ReadDecimal(); } } } public static string StringToBase64 (string src) { byte[] b = Encoding.Unicode.GetBytes(src); return Convert.ToBase64String(b); } public static string Base64ToString (string src) { byte[] b = Convert.FromBase64String(src); return Encoding.Unicode.GetString(b); } public static string DecimalToBase64 (decimal src) { byte[] b = DecimalToByteArray(src); return Convert.ToBase64String(b); } public static decimal Base64ToDecimal (string src) { byte[] b = Convert.FromBase64String(src); return ByteArrayToDecimal(b); } public static string IntToBase64 (int src) { byte[] b = BitConverter.GetBytes(src); return Convert.ToBase64String(b); } public static int Base64ToInt (string src) { byte[] b = Convert.FromBase64String(src); return BitConverter.ToInt32(b,0); } public static void Main() { byte[] data = { 0x06, 0x43, 0x5E, 0xFF, 0x34, 0xF0, 0x2D, 0x62, 0x78, 0x22, 0x15, 0x52, 0x5A, 0xDE, 0x0C, 0x59, 0x43, 0x43, 0xBD, 0xC2, 0xD5, 0x0F, 0x8D, 0xF5, 0xCE, 0x0C}; char[] base64data = new char[(int)(Math.Ceiling((double)data.Length / 3) * 4)]; Console.WriteLine("\nByte array encoding/decoding"); Convert.ToBase64CharArray(data, 0, data.Length, base64data, 0); Console.WriteLine(new String(base64data)); Console.WriteLine(BitConverter.ToString(Convert.FromBase64CharArray(base64data, 0, base64data.Length))); // Encode and decode a string. Console.WriteLine("\nString encoding/decoding"); Console.WriteLine(StringToBase64 ("Welcome to Visual C# Recipes from Apress")); Console.WriteLine(Base64ToString("ASDFGHJRTYUIFGHVBNDFGHRTJ")); // Encode and decode a decimal. Console.WriteLine("\nDecimal encoding/decoding"); Console.WriteLine(DecimalToBase64(212312312545.561231236696m)); Console.WriteLine(Base64ToDecimal("KDjBDFGHJKEPAATYUIOAAJAA==")); // Encode and decode an int. Console.WriteLine("\nInteger encoding/decoding"); Console.WriteLine(IntToBase64(32123)); Console.WriteLine(Base64ToInt("AAAzYsAAA==")); } }