简体   繁体   中英

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?

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM