3

I want to save/read an object to disk in c#. some of it's properties are not marked with [Serializable]. Is there any other way to save it? I don't care about the format of the object on the disk, I only want to dump it to the disk and read it.

Any suggestions?

2
  • You could save it was XML with property names and their values, if it's a fairly simple object anyhow. Commented May 29, 2012 at 15:42
  • I have remove my anwer as it has been down voter even if it was correct. Please have a look at stackoverflow.com/questions/1596317/… Commented May 29, 2012 at 15:57

2 Answers 2

3

An alternative to the suggested XmlSerializer would be protobuf-net. It's a .net implementation of Google's protobuf written by a SO/StackExchange own Marc Gravell. Note, you will have to have access to the objects since protobuf-net supports only custom classes that:

  • are marked as data-contract
  • have a parameterless constructor
  • for Silverlight: are public

If that doesn't work for you, you could either write your own solution or, depending on your scope, use an object db like eloquera.

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

2 Comments

+1 for Eloquera. It can work in the embedded mode, and serializes the objects of any complexity with no need for the [Serializable] attribute.
As init corrections: you do not require a parameterless constructor - ctor skipping is supported. And: you don't need an attributes such as DataContractAttribute - there is a separate API for configuring types without using attributes, ideal for types that you don't have access to.
1

The XmlSerializer class does not require an object to be marked as serializable, but it only saves the public fields and properties. If you need to serialize the private members, you are out of luck unless you write your own serializer.

2 Comments

BinaryFormatter will throw exception until each member of serialization target is marked by [Serializable]
Anyway the XmlSerializer do not require [Serializable] and can be used to serialize.

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.