I have a list of objects and I need to save that somewhere in my computer. I have read some forums and I know that the object has to be Serializable
. But it would be nice if I can get an example. For example if I have the following:
[Serializable]
public class SomeClass
{
public string someProperty { get; set; }
}
SomeClass object1 = new SomeClass { someProperty = "someString" };
But how can I store object1
somewhere in my computer and later retrieve?
I just wrote a blog post on saving an object's data to Binary, XML, or Json. You are correct that you must decorate your classes with the [Serializable] attribute, but only if you are using Binary serialization. You may prefer to use XML or Json serialization. Here are the functions to do it in the various formats. See my blog post for more details.
Binary
XML
Requires the System.Xml assembly to be included in your project.
Json
You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.
Example
You'll need to serialize to something: that is, pick binary, or xml (for default serializers) or write custom serialization code to serialize to some other text form.
Once you've picked that, your serialization will (normally) call a Stream that is writing to some kind of file.
So, with your code, if I were using XML Serialization:
Then, to deserialize:
NOTE: This code hasn't been compiled, let alone run- there may be some errors. Also, this assumes completely out-of-the-box serialization/deserialization. If you need custom behavior, you'll need to do additional work.
1. Restore Object From File
From Here you can deserialize an object from file in two way.
Solution-1: Read file into a string and deserialize JSON to a type
Solution-2: Deserialize JSON directly from a file
2. Save Object To File
from here you can serialize an object to file in two way.
Solution-1: Serialize JSON to a string and then write string to a file
Solution-2: Serialize JSON directly to a file
3. Extra
You can download Newtonsoft.Json from NuGet by following command
You can use the following:
**1. Convert the json string to base64string and Write or append it to binary file. 2. Read base64string from binary file and deserialize using BsonReader. **