Search code examples
c#windows-runtimewindows-rt

FileIO with Windows Rt and C#


Wow, is this way more complicated than it needs to be. Can someone explain to me why the following code works:

       string stringToWrite = "SomeStuff";
        Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;
        Windows.Storage.StorageFolder installedLocation = package.InstalledLocation;
        var files = await installedLocation.GetFilesAsync();
        foreach (Windows.Storage.StorageFile sf in files)
        {
            if (sf.Name.Equals("log.txt"))
            {
                await FileIO.AppendTextAsync(sf, stringToWrite);

            }
        }

And yet the following fails with AccessDenied:

      Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;
      Windows.Storage.StorageFolder installedLocation = package.InstalledLocation;
      var log = await installedLocation.GetFileAsync("log.txt");
      await FileIO.AppendTextAsync(log, stringToWrite);

The only difference is looping through the files returned by the GetFilesAsync method vs getting the file by name. By the way, getting the file by name works because if I misspell log.txt in GetFileAsync, I get an exception.

Very confusing....


Solution

  • You should not be using your installed location to write any files. It is supposed to be read-only as per MSDN: File Access/Permissions in Windows Store Apps:

    The app's install directory is a read-only location. You can’t gain access to the install directory through the file picker.

    You should be using either the Local, Roaming, or Temporary storage locations.

    See this link: MSDN: Quickstart Local Application Data