首页 > 解决方案 > System.IO.File.Create 正在返回 System.UnauthorizedAccessException 但仅针对一个文件

问题描述

背景

我有一些 C# 代码查询共享点,然后提供将特定文件下载到本地计算机上的文件夹中的能力。

奇怪的是,当我尝试下载文件 A 时,它没有问题。当我尝试下载文件 B 时,发生了 2 件奇怪的事情:

  1. “exists”变量总是返回为真——即使文件的本地副本不存在。
  2. 当我单击替换本地文件的选项时,当它遇到 .Create() 方法时,它会抛出 System.UnauthorizedAccessException 错误...

所以具体来说,当我尝试下载时:

C:\Users\me\AppData\Local\Packages\d87c4dcd-a0b6-4d3e-a529-72da28f897e4_4p54yvdgfzqvw\LocalState\ABCDoc.docx

它工作正常。

当我尝试下载

C:\Users\me\AppData\Local\Packages\d87c4dcd-a0b6-4d3e-a529-72da28f897e4_4p54yvdgfzqvw\LocalState\123Doc.docx

我总是得到一个消息框,说文件已经存在,我要替换吗?我会点击是。然后它因未经授权的访问错误而失败。

我试过的

在调试模式下运行时,我劫持了文件名并将其更改为新名称,下载/保存有效。

这是代码:

  protected async void DownloadFile(object sender, EventArgs e)
    {
        var menuItem = sender as MenuItem;
        if (menuItem != null)
        {
            //grab the details of the file currently selected 
            var selectedFile = (Microsoft.Graph.ListItem)menuItem.BindingContext;
            
            //check if the file already exists in the local workspace.  if it does prompt.  if not just download. 
            var driveItemPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), selectedFile.DriveItem.Name);
            var exists = System.IO.File.Exists(driveItemPath);
            if (exists)
            {
                if (!await DisplayAlert("Download", "Download and replace local copy of " + selectedFile.DriveItem.Name + "?", "Yes", "No"))
                {
                    return;
                }
            }

            try
            {
                using (var stream = await App.GraphClient.Sites[siteID].Drive.Items[selectedFile.DriveItem.Id].Content.Request().GetAsync())
                {
                    var driveItemFile = System.IO.File.Create(driveItemPath);
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.CopyTo(driveItemFile);
                    driveItemFile.Close(); //also a stream which needs to be Dispose()d.
                }
                DisplayAlert("Download", selectedFile.DriveItem.Name + " successfully downloaded", "OK");
            }
            catch (Exception ex)
            {
                Console.WriteLine("DOWNLOAD FAILED WITH: " + ex.Message);
                DisplayAlert("ERROR", selectedFile.DriveItem.Name + " failed with: " + ex.Message, "OK");
            }
            

        }
    }

标签: c#xamluwpsystem.io.file

解决方案


推荐阅读