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

4

我正在编写一个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文件,但是它是空的。我做错了什么吗?难道不应该将对象写入文件中吗?

3
你是否关闭了 StreamWriter?或者更好的方式是使用 using (var str = new StreamWriter(isoStream)) { str.Write(jsonFile); } 语句来包装它?请参阅“如何正确使用 StreamWriter 类?”(链接:https://dev59.com/Omgu5IYBdhLWcg3wP01m) - dbc
没有,我没有关闭它。 - nick
那么问题就在这里。如果您不关闭StreamWriter,则您写入的某些内容可能无法刷新到磁盘。 - dbc
2个回答

4
问题在于你没有关闭流。
在Windows中进行文件I/O时,在操作系统级别上有缓冲区,而.NET甚至可能在API级别上实现缓冲区。这意味着,除非你告诉该类“我已经完成了”,否则它永远不会知道何时确保将这些缓冲区传播到磁盘盘片。
你应该稍微改写你的代码,像这样:
using (StreamWriter str = new StreamWriter(isoStream))
{
    str.Write(jsonFile);
}

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


0

我使用这些。应该对你也有效。

    public async Task SaveFile(string fileName, string data)
    {
        System.IO.IsolatedStorage.IsolatedStorageFile local =
            System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();

        if (!local.DirectoryExists("MyDirectory"))
            local.CreateDirectory("MyDirectory");

        using (var isoFileStream =
                new System.IO.IsolatedStorage.IsolatedStorageFileStream(
                    string.Format("MyDirectory\\{0}.txt", fileName),
                    System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite,
                        local))
        {
            using (var isoFileWriter = new System.IO.StreamWriter(isoFileStream))
            {
                await isoFileWriter.WriteAsync(data);
            }
        }
    }

    public async Task<string> LoadFile(string fileName)
    {
        string data;

        System.IO.IsolatedStorage.IsolatedStorageFile local =
            System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();

        using (var isoFileStream =
                new System.IO.IsolatedStorage.IsolatedStorageFileStream
                    (string.Format("MyDirectory\\{0}.txt", fileName),
                    System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read,
                    local))
        {
            using (var isoFileReader = new System.IO.StreamReader(isoFileStream))
            {
                data = await isoFileReader.ReadToEndAsync();
            }
        }

        return data;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接