C# - Save object to JSON file

前端 未结 2 778
盖世英雄少女心
盖世英雄少女心 2021-01-13 20:00

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 = JsonConve         


        
2条回答
  •  遥遥无期
    2021-01-13 20:25

    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.

提交回复
热议问题