Question

I use Json files for storing app-related objects. Reading works but I'm confused about writing to the file.

private static void WriteFileContentsAsync(string content)
{
    var local = IsolatedStorageFile.GetUserStoreForApplication(); //(new Uri("Common/DataModel/EventsData.json", UriKind.Relative));
    var eventsFile = local.OpenFile("Common/DataModel/EventsData.json", FileMode.Open);

    using (StreamWriter writer = new StreamWriter(eventsFile))
    {
        writer.WriteAsync(content);
    }
}

I can't open the file located in my project -> Common/DataModel/EventsData.json The exception tells me that the operation is not permitted.

This is how I read from the same file:

private static string ReadFileContents()
{
    var ResrouceStream = Application.GetResourceStream(new Uri("Common/DataModel/EventsData.json", UriKind.Relative));
    if (ResrouceStream != null)
    {
        using (Stream myFileStream = ResrouceStream.Stream)
        {
            if (myFileStream.CanRead)
            {
                StreamReader myStreamReader = new StreamReader(myFileStream);
                return myStreamReader.ReadToEnd();
            }
        }
    }
    return string.Empty;
}

But myFileStream.CanWrite is false.

What would be the correct alternative?

EDIT

I tried this another way, but the file it should write to doesn't change and no errors occur:

private static void WriteFileContentsAsync(string content)
{
    FileStream fs = new FileStream("Common/DataModel/EventsData.json",FileMode.Open,FileAccess.Write);

    if (fs.CanWrite)
    {
        using (StreamWriter writer = new StreamWriter(fs))
        {
            writer.WriteAsync(content);
        }
    }
}
Was it helpful?

Solution

Can't you just use:

IsolatedStorageFile isoFile;
isoFile = IsolatedStorageFile.GetUserStoreForApplication();

// Open or create a writable file.
IsolatedStorageFileStream isoStream =
    new IsolatedStorageFileStream("Common/DataModel/EventsData.json",
    FileMode.OpenOrCreate,
    FileAccess.Write,
    isoFile);

StreamWriter writer = new StreamWriter(isoStream);

OTHER TIPS

This has to be good content for one of those "I can't be the only one" memes!

I was constantly checking my project folder to see if the file has changed but I should have checked the install folder (somewhere in C:\data...). Writing does actually work :/

Hopefully, these examples and this answer will help many by-passers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top