C# - Save object to JSON file

僤鯓⒐⒋嵵緔 提交于 2019-12-01 06:51:20

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.

I use these. Shoud work for you as well.

    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;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!