473,320 Members | 1,861 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Serializing a Hashtable

I know how to take a single hashtable, and then use a binaryformatter
and a filestream to dump it to a file, but I need to serialize and
deserialize a hashtable inside a class. I've been trying this:

[XmlIgnore]
public Hashtable Directions;

public byte[] DirectionsSerialized
{
get
{
byte[] bData = new byte[1024];
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream(bData);
memoryStream.Position = 0;
formatter.Serialize(memoryStream, Directions);

return bData;
}
set
{
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(value, 0, value.Length);
BinaryFormatter bf = new BinaryFormatter();
memoryStream.Position = 0;
Directions = (Hashtable)bf.Deserialize(memoryStream);
}
}

Which appears to serialize fine, but upon deserialization, it throws an
error:

"'', hexadecimal value 0x1B, is an invalid character. Line 299,
position 18."

Thanks guys.

Nov 17 '05 #1
3 10103
Mio,

A few things.

The first is that you don't really have to initialize the memory stream
with your array when serializing the instance, since it will allocate space
as needed when the serializer writes to it.

The other thing about this is that when you pass the byte array to the
constructor, it makes the memory stream fixed-size. So if you need more
than one kilobyte for the serialized instance, it will throw an exception.

Additionally, when you are returning the byte array, it contains extra
bytes that are not part of the serialized instance (in the case where you
need less than 1K).

Your get code should look like this:

// Create the formatter.
BinaryFormatter formatter = new BinaryFormatter();

// Create the stream.
using (MemoryStream memoryStream = new MemoryStream())
{
// No need to set the position, since it is already at 0.
// Serialize the instance.
formatter.Serialize(memoryStream, Directions);

// Return the array. This will be properly sized.
return memoryStream.ToArray();
}

Now, when dealing with deserializing the instance, your code should work
just fine. However, it could stand to be cleaned up, like so:

// Pass the value into the memory stream, since we are just reading.
using (MemoryStream memoryStream = new MemoryStream(value))
{
// Create the formatter.
BinaryFormatter bf = new BinaryFormatter();

// Set the hashtable.
Directions = (Hashtable) bf.Deserialize(memoryStream);
}

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
<Mi*********@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
I know how to take a single hashtable, and then use a binaryformatter
and a filestream to dump it to a file, but I need to serialize and
deserialize a hashtable inside a class. I've been trying this:

[XmlIgnore]
public Hashtable Directions;

public byte[] DirectionsSerialized
{
get
{
byte[] bData = new byte[1024];
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream(bData);
memoryStream.Position = 0;
formatter.Serialize(memoryStream, Directions);

return bData;
}
set
{
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(value, 0, value.Length);
BinaryFormatter bf = new BinaryFormatter();
memoryStream.Position = 0;
Directions = (Hashtable)bf.Deserialize(memoryStream);
}
}

Which appears to serialize fine, but upon deserialization, it throws an
error:

"'', hexadecimal value 0x1B, is an invalid character. Line 299,
position 18."

Thanks guys.
Nov 17 '05 #2
Thanks Nicholas.

That works perfectly.

Nicholas Paldino [.NET/C# MVP] wrote:
Mio,

A few things.

The first is that you don't really have to initialize the memory stream
with your array when serializing the instance, since it will allocate space
as needed when the serializer writes to it.

The other thing about this is that when you pass the byte array to the
constructor, it makes the memory stream fixed-size. So if you need more
than one kilobyte for the serialized instance, it will throw an exception.

Additionally, when you are returning the byte array, it contains extra
bytes that are not part of the serialized instance (in the case where you
need less than 1K).

Your get code should look like this:

// Create the formatter.
BinaryFormatter formatter = new BinaryFormatter();

// Create the stream.
using (MemoryStream memoryStream = new MemoryStream())
{
// No need to set the position, since it is already at 0.
// Serialize the instance.
formatter.Serialize(memoryStream, Directions);

// Return the array. This will be properly sized.
return memoryStream.ToArray();
}

Now, when dealing with deserializing the instance, your code should work
just fine. However, it could stand to be cleaned up, like so:

// Pass the value into the memory stream, since we are just reading.
using (MemoryStream memoryStream = new MemoryStream(value))
{
// Create the formatter.
BinaryFormatter bf = new BinaryFormatter();

// Set the hashtable.
Directions = (Hashtable) bf.Deserialize(memoryStream);
}

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
<Mi*********@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
I know how to take a single hashtable, and then use a binaryformatter
and a filestream to dump it to a file, but I need to serialize and
deserialize a hashtable inside a class. I've been trying this:

[XmlIgnore]
public Hashtable Directions;

public byte[] DirectionsSerialized
{
get
{
byte[] bData = new byte[1024];
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream(bData);
memoryStream.Position = 0;
formatter.Serialize(memoryStream, Directions);

return bData;
}
set
{
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(value, 0, value.Length);
BinaryFormatter bf = new BinaryFormatter();
memoryStream.Position = 0;
Directions = (Hashtable)bf.Deserialize(memoryStream);
}
}

Which appears to serialize fine, but upon deserialization, it throws an
error:

"'', hexadecimal value 0x1B, is an invalid character. Line 299,
position 18."

Thanks guys.


Nov 17 '05 #3


Mi*********@gmail.com wrote:
I know how to take a single hashtable, and then use a binaryformatter
and a filestream to dump it to a file, but I need to serialize and
deserialize a hashtable inside a class.


You could simply mark the containing class serializable, and let the
caller store that, but lookin at you example code I suspect you wish to
run some transformation when serializing/deserializing.

If that is the case, you can use a variant of the Memento pattern, where
you generate an opaque "memento" object that can be used to restore the
state. This object can be serialized by the caller if need be.

// not serializable
public class Foo {
// loads of state in here, perhaps duplicated
// references for efficiency and whatnot

[Serializable]
protected class Memento {
public Hashtable Directions;
public Memento(Foo foo) {
this.Directions = extract_direction_state(foo);
}
}
public object DirectionMemento {
get {
return new Memento(()); }
set {
reestablish_direction_state((Memento)value); }
}
}
}

The user will then do:

Foo foo = new Foo();
// lots of stuff, then need to save foo state:
someFormatter.Serialize(someStream, foo.DirectionMemento);
// do stuff, later restore foo state:
foo.DirectionMemento = someFormatter.Deserialize(someStream);

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Don McNamara | last post by:
Hi, I've hit quite a strange problem with XmlSerializer on my W2K3 server. When I serialize/deserialize using an exe on my local computer (XP), everything works fine. When I put the code out on...
0
by: Kenneth Baltrinic | last post by:
Is the following code correct for serializing a quasi-single class, that is a class that has a descreet (though more than one, so not a true singleton) number of static instances and no dynamically...
5
by: francois | last post by:
First of all I would to to apologize for resending this post again but I feel like my last post as been spoiled Here I go for my problem: Hi, I have a webservice that I am using and I would...
2
by: Brian Keating | last post by:
hi there, has anyone had success in serializing a 2.0 case sensivite hashtable ie. private Hashtable m_itemsById = new Hashtable( new CaseInsensitiveHashCodeProvider(), new...
5
by: Victor Paraschiv | last post by:
I need to serialize into an XML file a hashtable. From MSDN at XmlSerializer:...
0
by: JackRazz | last post by:
I'm trying to serialize a collection to a file stream by serializing each object individually. The code below works fine with the BinaryFormatter, but the SoapFormatter reads the first object and...
0
by: Michael Maercker | last post by:
Hi! I'm about to go nuts over my serializing problem. This is my situation: I have a Data-Class that can have children of the same class which are stored in a hashtable, i.e: X has A as a...
2
by: Curtis | last post by:
Does anyone have any examples of serializing a hashtable? I tried to make a copy of the hash table using the .clone method but per MS documention it creates a shallow copy of the object. I am...
2
by: Jen | last post by:
I have a Hashtable serializing to a binary file ok but I really would like the file to be in XML format or other readable format. I DO NOT want to change all my code, I want to keep the Hashtable...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.