2

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
  • When you say you have a "list", exactly what do you mean? Commented Oct 25, 2009 at 19:42

3 Answers 3

6

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...

Sign up to request clarification or add additional context in comments.

2 Comments

Well, yes. I am normally a pedant about this, but for MemoryStream it truly makes no difference. I'll edit, just for you ;-p
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!
1

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.

2 Comments

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); } }
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; } }
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.