Monday, March 07, 2005
Using MemoryStream .NET
//writing to Memory stream
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.FlushFinalBlock();
//getting the bytes from memory stream and converting them to a string
byte[] memoryTextBytes = memoryStream.ToArray();
string originalText = Convert.ToBase64String(memoryTextBytes );
//reading from memoryStream
byte[] memoryTextBytes2 = new byte[memoryStream.Length]; memoryStream.Seek(0,SeekOrigin.Begin);
int readByteCount = memoryStream.Read(memoryTextBytes2 , 0, memoryTextBytes2 .Length);
memoryStream.Close();
string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, readByteCount);
--------------------------------------------------------------------------------------
using MemoryStream to BinarySerialize into memory
--------------------------------------------------------------------------------------
MemoryStream t = new MemoryStream();
BinaryFormatter myFormatter = new BinaryFormatter();
myFormatter.Serialize(t, someObject); //serialize some object
byte[] plainTextBytes = new byte[t.Length];
t.Seek(0,SeekOrigin.Begin);
int readByteCount = t.Read(plainTextBytes, 0, plainTextBytes.Length);
t.Close();
//plainText contains the serialized string
string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, readByteCount);
///deserialization
byte[] stringAsBytes = Encoding.UTF8.GetBytes(plainText);
t = new MemoryStream(stringAsBytes);
object newO = myFormatter.Deserialize(t) ;
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment