C# - 将对象保存到 JSON 文件

标签 c# json silverlight windows-phone isolatedstorage

我正在编写 Windows Phone Silverlight 应用程序。我想将一个对象保存到一个 JSON 文件中。我编写了以下代码。

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);

这足以创建一个 JSON 文件,但它是空的。难道我做错了什么?这不是应该将对象写入文件吗?

最佳答案

问题是您没有关闭流。

Windows 中的文件 I/O 在操作系统级别有缓冲区,而 .NET 甚至可能在 API 级别实现缓冲区,这意味着除非你告诉类“现在我完成了”,否则它永远不知道什么时候以确保这些缓冲区一直传播到盘片。

你应该像这样稍微重写你的代码:

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

using (...) { ... } 将确保当代码离开 block 时,{ ... } 部分将调用 IDisposable.Dispose在对象上,在本例中将刷新缓冲区并关闭底层文件。

关于C# - 将对象保存到 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36786411/

相关文章:

c# - Xamarin.iOS - PIE 警告

javascript - 查找 json 名称/值对的长度

c# - 如何从字符串中去除非字母数字字符(包括空格)?

c# - RavenDB Query <T>总是比加载<T>快

php - 从浏览器访问网络服务器。不是来自xcode

silverlight - WP7 NavigationService.Navigate传递指针而不使用全局变量?

c# - 绑定(bind)必须是可观察的集合吗?为什么这不起作用?

c# - 在图像按钮中加载图像

自定义语言的 C# 所见即所得编辑器

java.io.IOException : unexpected end of stream on okhttp3. 地址@e31061fc