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