[UWP] Bug report: StorageFile.RenameAsync throws an UnauthorizedAccessException with NameCollisionOption.ReplaceExisting

Julien Théron 6 Reputation points
2020-08-17T20:01:56.747+00:00

We recently discovered an issue with the StorageFile API while renaming a file created in a picked folder.

Here's the sample code for the issue (just put it in the MainPage's Loaded event):

var picker = new FolderPicker
{
  FileTypeFilter = { "*" }
};

var folder = await picker.PickSingleFolderAsync();
if (folder != null)
{
  await Task.Run(async () =>
  {
    var file = await folder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
    await file.RenameAsync("My File.txt", NameCollisionOption.ReplaceExisting);
  });
}

The issue doesn't occur with the other NameCollisionOptions, or if you remove the call to Task.Run.

The workaround I found is to use the StorageFile.MoveAsync API instead of RenameAsync:

await file.MoveAsync(folder, "My File.txt", NameCollisionOption.ReplaceExisting);

Thanks.

Universal Windows Platform (UWP)
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Richard Zhang-MSFT 6,936 Reputation points
    2020-08-18T02:23:47.97+00:00

    Hello,

    Welcome to Microsoft Q&A.

    It is a permission design, if you want to continue using RenameAsync, you need to add broadFileSystemAccess capability:

    package.txt

    After adding the corresponding capability, you need to enable the access permission of the application in

    Settings -> Pivacy -> File system

    After this, the method can be executed normally, which also confirms that this is a permission design.

    It is a bit complicated, you also mentioned that you found a workaround, so you can continue to use it.

    ---

    Update

    In addition to using broadFileSystemAccess, there is another method, which is to add folders to FutureAccessList, which is also a way to increase application access permissions. After testing, it works.

    if (folder != null)  
    {  
        StorageApplicationPermissions.FutureAccessList.Add(folder);  
        var file = await folder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);  
        await file.RenameAsync("My File.txt", NameCollisionOption.ReplaceExisting);  
    }  
    

    Thanks.