0

I am trying to save a JSON file in the app folder, i am able to read the data from this file, but i am not able to write data in this file.

data.json is marked as "Content" in the file properties.

class Json
{
    private string data;
    private const string value1key = "value1";
    private const string value2key = "value2";
    private const string value3key = "value3";

    StorageFile file;
    StorageFolder folder;

    private void File()
    {
        folder = Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Data").AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
        //file = StorageFile.GetFileFromApplicationUriAsync(new Uri(@"ms-appx:///data.json")).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
        file = folder.GetFileAsync("data.json").AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
    }

    public Json()
    {
        File();
    }

    public string Read()
    {
        return (FileIO.ReadTextAsync(file).AsTask().ConfigureAwait(false).GetAwaiter().GetResult());
    }

    public async void Save()
    {
        JsonObject jsonObject = new JsonObject();
        jsonObject["value1"] = JsonValue.CreateNumberValue(Data._value1);
        jsonObject["value2"] = JsonValue.CreateNumberValue(Data._value2);
        jsonObject["value3"] = JsonValue.CreateNumberValue(Data._value3);

        string newData = jsonObject.Stringify();
        await FileIO.WriteTextAsync(file, newData);
        //FileIO.WriteTextAsync(file, newData).AsTask().ConfigureAwait(true).GetAwaiter();
    }
}

I got this error: System.UnauthorizedAccessException: 'Denied access. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'

If the problem has no solution, is there another way to save application data?

1 Answers1

0

All files in App folder are read-only. So try setting the FileAttributes as Normal before writing data in that file. You can do it using below code

File.SetAttributes(file, FileAttributes.Normal);
Vijay Nirmal
  • 5,239
  • 4
  • 26
  • 59
  • I got this: System.UnauthorizedAccessException: 'Access to the path 'C:\Users\Carlos Giovano\documents\visual studio 2017\Projects\App1\App1\bin\x86\Debug\AppX\Data\data.json' is denied.'. I tested this code in the previous version of VS (2015) with anniversary update, and, worked! i don't know how and why. – Carlos Giovano Jul 01 '17 at 21:00
  • Did you try by running VS in Admin? Did you try the above code? – Vijay Nirmal Jul 02 '17 at 05:29