C# - Save object to JSON file

tony picture tony · Apr 22, 2016 · Viewed 17.3k times · Source

I'm writing a Windows Phone Silverlight app. I want to save an object to a JSON file. I've written the following piece of code.

string jsonFile = JsonConvert.SerializeObject(usr);
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("users.json", FileMode.Create, isoStore);

StreamWriter str = new StreamWriter(isoStream);
str.Write(jsonFile);

This is enough to create a JSON file but it is empty. Am I doing something wrong? Wasn't this supposed to write the object to the file?

Answer

Lasse V. Karlsen picture Lasse V. Karlsen · Apr 22, 2016

The problem is that you're not closing the stream.

File I/O in Windows have buffers at the operating system level, and .NET might even implement buffers at the API level, which means that unless you tell the class "Now I'm done", it will never know when to ensure those buffers are propagated all the way down to the platter.

You should rewrite your code just slightly, like this:

using (StreamWriter str = new StreamWriter(isoStream))
{
    str.Write(jsonFile);
}

using (...) { ... } will ensure that when the code leaves the block, the { ... } part, it will call IDisposable.Dispose on the object, which in this case will flush the buffers and close the underlying file.