using c#, VS2013, windows store app

In simple program have a file with some data saved in JSON format. I'll try to add new data to this file and then store it.

enter image description here

Try to save file in JSON with next code:

string result = await JsonConvert.SerializeObjectAsync(groups);
//get file path
string pathOfFile = Path.GetDirectoryName(file.Path); //get path
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(pathOfFile); //create dir by path

StringBuilder builder = new StringBuilder();
builder.Append(folder.Path);
builder.Append("\\EventsData.json");

Uri uriToSave = new Uri(builder.ToString());
//create file
StorageFile fileToWrite = 
    await StorageFile.GetFileFromApplicationUriAsync(uriToSave);
using (IRandomAccessStream stream =
    await file.OpenAsync(FileAccessMode.ReadWrite))
{
    // write the JSON file
     using (DataWriter textWriter = new DataWriter(stream))
    {
        textWriter.WriteString(result);
          await textWriter.StoreAsync();
    }
}

But during executing code StorageFile fileToWrite = await StorageFile.GetFileFromApplicationUriAsync(uriToSave); got exception System.ArgumentException

During debagging got next Uri

enter image description here

Question - why i got such exception and if I'm wrong - how to save file in windows store app in required directory?

Also look MSDN sample for writing data to file, and use code like in tutorial but got System.UnauthorizedAccessException:

StorageFile sampleFile = await folder.CreateFileAsync("EventsData.json", CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, result);

Why Access denied or I missing something?

有帮助吗?

解决方案

You cannot write to the install directory without explicit permission from the user.

Here is the protocol instead:

  • At first startup, check to see if there is a file in the local data folder (ApplicationDataContainer), if not, read in the file from the install directory.
  • Write out a copy of the file to the local app data folder (Check out guides on ApplicationDataContainer for more info there)
  • Edit this file freely.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top