C # - Save an object in a JSON file

I am writing a Windows Phone Silverlight application. I want to save an object to a JSON file. I wrote the following code snippet.

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

This is enough to create a JSON file, but it is empty. Am I doing something wrong? Wasn’t it supposed to write the object to a file?

+4
source share
2 answers

The problem is that you are not closing the stream.

- Windows , .NET API, , , " ", , , .

, :

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

using (...) { ... } , , , { ... }, IDisposable.Dispose , .

+1

. .

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

All Articles