tags:

views:

455

answers:

3

I have a custom list which I want to embed as a resource so it can be copied out with each new install. However, my list is serialized as a binary file and when I add it as a resource I can't just copy it out because C# treats it as a byte array. I need to be able to convert this byte array back to my custom list when I extract the file from my resources. Can someone give me an idea of how to accomplish this conversion?

Thanks!

+1  A: 

How is the list being serialized? You should have access to an equivalent Deserialize() method whose result you can cast back to the original list type.

dahlbyk
This is how I serialize the resource.if (!FiOhaus.Exists) { DirectoryUtil.DoesDataFileExist(OhausScale); using (Stream St = new FileStream(OhausScale, FileMode.OpenOrCreate)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(St, Resources.Ohaus_Adventure_Pro); } }
Nathan
This is how I deserialize it the file back to a list. using (Stream St = new FileStream(_directory + modelName + ".dat", FileMode.Open)) { if (St.Length > 0) { BinaryFormatter formatter = new BinaryFormatter(); Settings = (List<LocalScales>)formatter.Deserialize(St); isLoaded = true; } }
Nathan
+1  A: 

You need to deserialize the byte array back into an instance of your list. The way to do this depends on the mechanism by which you serialized it. If you used a BinaryFormatter to serialize it, for example, use the same to deserialize.

HTH, Kent

Kent Boogaart
+5  A: 

In what way have you serialized it? Normally you would just reverse that process. For example:

BinaryFormatter bf = new BinaryFormatter();
using(Stream ms = new MemoryStream(bytes)) {
    List<Foo> myList = (List<Foo>)bf.Deserialize(ms);
}

Obviously you may need to tweak this if you have used a different serializer! Or if you can get the data as a Stream (rather than a byte[]) you can lose the MemoryStream step...

Marc Gravell
Don't forget to dispose the `MemoryStream`, of course!
Noldorin
Well, yes. I am normally a pedant about this, but for `MemoryStream` it **truly** makes no difference. I'll edit, just for you ;-p
Marc Gravell
Ah I see. I was taking the resource and serializing it out to a file and then trying to re-serialize back into my list. This makes more sense.Thanks!
Nathan