C# - Save object to JSON file C# - Save object to JSON file json json

C# - Save object to JSON file


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