Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42880

UnauthorizedAccessException during storageFolder.CreateFileAsync

I have the following piece of code

    // Point to c:\users\yancheng\documents\visual studio 2012\Projects\App5\App5\bin\x86\Debug\AppX
    StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

    StorageFile file = await storageFolder.CreateFileAsync("1000.txt");

    if (file != null)
    {
        using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            using (DataWriter dataWriter = new DataWriter(writeStream))
            {
                dataWriter.WriteInt32(1000);
            }
        }
    }

I have enabled all permission through Package.appxmanifest. However, I am not sure why I am still getting UnauthorizedAccessException during storageFolder.CreateFileAsync.

Any other things I had missed out?

Upvotes: 0

Views: 3368

Answers (2)

Jürgen Bayer
Jürgen Bayer

Reputation: 3023

You are trying to create a file in the installation folder of the app. This location is a read-only location (see http://msdn.microsoft.com/en-us/library/windows/apps/hh967755.aspx).

Strangely copying files to this folder and deleting files from it is possible if the app was installed by Visual Studio, what I reported as a bug in Microsoft Connect. All in all Apps should not be able to change any content of the installation folder.

Apps are only allowed to write to the folders reached through ApplicationData and the KnownFolders. In latter case corresponding capabilities and file types must be declared.

Upvotes: 2

Jennifer Marsman - MSFT
Jennifer Marsman - MSFT

Reputation: 5225

From your comments above, I'm assuming that you've checked the "Documents Library" capability in the package.appxmanifest.

Check out the remarks in the documentation for StorageFolder.CreateFileAsync. It says: "If you try to create a file in a virtual folder like a library or a file group, this method may fail." Then in the Example section, it shows a different way to create a new file in the Documents library using Windows.Storage.KnownFolders.documentsLibrary.createFileAsync(). Can you try that and see if it works?

Upvotes: 1

Related Questions