c# - System.IO.File.Create 正在返回 System.UnauthorizedAccessException 但仅针对一个文件
问题描述
背景
我有一些 C# 代码查询共享点,然后提供将特定文件下载到本地计算机上的文件夹中的能力。
奇怪的是,当我尝试下载文件 A 时,它没有问题。当我尝试下载文件 B 时,发生了 2 件奇怪的事情:
- “exists”变量总是返回为真——即使文件的本地副本不存在。
- 当我单击替换本地文件的选项时,当它遇到 .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");
}
}
}
解决方案
推荐阅读
- java - 在 testng.xml 之外使用 IAnnotationTransformer
- scala - 如何用Scala中的另一种方法包装具有隐含的方法?
- amazon-web-services - 我可以在没有“skipper”入口的情况下使用“kube-ingress-aws-controller”吗?
- makefile - 输入包装foreach的自定义定义后如何扩展变量?
- python - 如何使用 Django 模型和管理器从 PostgreSQL 查询整个数据集并使用 Ajax 渲染前端
- python - 如何计算两个日期列之间的时间差
- javascript - 使用 Spring Boot 构建短信和视频通话应用程序
- python - 在一行中关闭 xml 标记
- amazon-web-services - 了解 AWS ECS 中的 CPU 单元
- c++ - 如何进行参数包的分组或成对折叠?