Thursday, November 8, 2018

Save objects in Visual Studio for reuse later

One easy way to save an object while debugging in Visual Studio so that you can use it later for troubleshooting, or maybe use in LINQPad is to serialize the object to disk.

All the libraries you need are built into .NET and can be done in the Immediate Prompt in Visual Studio.

Save the Object to disk

string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myObject);
System.IO.File.WriteAllText($@"c:\dev\{nameof(myObject)}.json", json);

Read the Object from disk

string json = System.IO.File.ReadAllText(@"c:\dev\myObject.json");
           
var company = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<MyClass>(json);

The caveat to this is that you will need the MyClass available when you bring it back to life.You can also pass Object instead of MyClass if you don't have it.