0

I am communicating with a device with its provided dll drivers in C# using VS Express 2013. As a result I'm using some classes defined by the producer. I want to save/read some objects to a file but I cannot save them to a binary file directly because:

  1. These objects are not Serializable
  2. I cannot add Serializable to classes since they are provided with dll

An annoying solution is to save all information in the objects one by one, i.e. saving all integers, arrays, bools, etc.

using (Stream stream = File.Open(fileName, FileMode.OpenOrCreate))
{
    var bF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    bF.Serialize(stream, saveObj.measurementType);
    bF.Serialize(stream, saveObj.Results);
    bF.Serialize(stream, saveObj.TimeStamp);
    bF.Serialize(stream, saveObj.TXPowerSet);
    bF.Serialize(stream, saveObj.ValidCalFlags);
}

Is there a better solution so that I can save/read saveObj in a few steps?

It does not necessarily have to be a binary file.

Edit: Revised the question according to comments.

5
  • 1
    So your question is how to serialize a class that's not serializable? Does it have to be binary? Could you use something else (like XML or JSON)? Commented Dec 3, 2014 at 13:42
  • 1
    Anything is fine as long as I can save/read file without dealing with all of the variables. Commented Dec 3, 2014 at 13:45
  • Please edit your question to include your actual requirements. Commented Dec 3, 2014 at 13:46
  • I have edited accordingly to the suggestions. Commented Dec 3, 2014 at 13:51
  • If XML/JSON do not suit you, you can use MessagePack - github.com/msgpack/msgpack-cli/wiki/Quick-Start Commented Dec 3, 2014 at 14:02

1 Answer 1

3

No. The reason Serializable is required is because binary serialization serializes all fields of a class (public and private). You have to explicitly grant permission to serialize so one cannot serialize any class that may have sensitive information.

Look at XmlSerializer and JsonSerializer. Those methods only serialize public data, so express consent is not required.

You can use the same classes to deserialize as well, with the caveat that the public properties must be writable.

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

2 Comments

Can I read saved data directly back to an object? Or does this option only simplify the saving part?
Thanks, I chose the longer path of writing/reading everything for now.

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.