How to serialize objects to a string then write to database

  • Thread starter Thread starter John
  • Start date Start date
J

John

Hi,

I need to serialize one of my objects to the database as a
string, i.e the database field is a varchar. I can't see
a way of doing without doing the following:

MemoryStream ms = new MemoryStream();

IFormatter Iformatter = new BinaryFormatter();
Iformatter.Serialize(ms,myObject);
byte[] bMyObject = ms.GetBuffer();
foreach(byte oByteChar in bFilterConditions)
{
strObjectToSave += Convert.ToChar(oByteChar);
}

drMyObject.VALUE = strObjectToSave;

Is there a better way of doing this?, I need to do the
above when I'm deserializing the object as well.

Any help much appreciated.

John
 
Hi John,

There at least two ways:
Using either System.Runtime.Serialization.Formatters.Soap.SoapFormatter or
XMLSerializer class that will produce string result.
Or, encode your binary result using one of derived System.Text.Encoding
classes.
 
There at least two ways:
Using either System.Runtime.Serialization.Formatters.Soap.SoapFormatter or
XMLSerializer class that will produce string result.
Or, encode your binary result using one of derived System.Text.Encoding
classes.

I would strongly advise *not* encoding binary data using
System.Text.Encoding classes - instead, Base64 or Base16 encode it. The
encoding classes are not meant to encode arbitrary binary data as text.
 
On the subject of Radix 64 (uuencoding) what is the storage footprint of a
base 64 file over a simple BinHex field (2N where N = file size as it takes
2 chars per byte in an XML BinHex element).

What is the storage size of Base64?

BinHex = 2N
Base64 = ???

Thanks
 
Thanks that works fine, I'm using the ASCIIdecoder at the
moment what is the base64, base 16 encoder?
 
Hi Jon,

Yes, you are right it is better if you use Base64 to store data in database.
 
On the subject of Radix 64 (uuencoding) what is the storage footprint of a
base 64 file over a simple BinHex field (2N where N = file size as it takes
2 chars per byte in an XML BinHex element).

What is the storage size of Base64?

BinHex = 2N
Base64 = ???

Base 64 encodes 6 bits per character, so the final size is 4N/3
characters.
 
John said:
Thanks that works fine, I'm using the ASCIIdecoder at the
moment

In that case you're likely to lose data if any of your bytes are >127.
what is the base64, base 16 encoder?

See Convert.ToBase64String and Convert.FromBase64String. Base16
encoding is just hex, eg the byte array {0x23, 0x56} would get encoded
as "2356". I don't know if there are any built-in Base16 encoders in
..NET, but it's trivial to write one.
 
Back
Top