You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

System.IO.File.Create仅对单文件返回System.UnauthorizedAccessException问题求助

问题原因

1. 路径构造错误

你的代码用Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)获取的路径是系统本地应用数据根目录C:\Users\用户名\AppData\Local,而你预期写入的UWP应用沙盒LocalState目录,正确的获取方式应该是Windows.Storage.ApplicationData.Current.LocalFolder.Path。
构造的路径不在应用有权限访问的范围内,是触发UnauthorizedAccessException错误的核心原因。

2. File.Exists始终返回true的原因

你当前拼接的路径实际指向C:\Users\me\AppData\Local\123Doc.docx,该位置确实存在同名文件,所以检测结果为真。而ABCDoc.docx在该位置不存在,所以检测逻辑表现正常。

3. 流未正确释放的潜在问题

你代码中System.IO.File.Create返回的文件流没有做释放管理,就算路径正确,只要之前操作过同名文件没有释放流,文件会被系统锁定,再次创建时也会触发权限类错误。

修复后的代码

protected async void DownloadFile(object sender, EventArgs e)
{
    var menuItem = sender as MenuItem;
    if (menuItem != null)
    {
        var selectedFile = (Microsoft.Graph.ListItem)menuItem.BindingContext;
        // 修正LocalState路径获取方式
        var localFolderPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
        var driveItemPath = Path.Combine(localFolderPath, selectedFile.DriveItem.Name);
        // 调试时可以输出确认路径是否符合预期
        Console.WriteLine("目标保存路径:" + driveItemPath);
        
        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())
            {
                // 给文件流加using自动释放,无需手动Close
                using (var driveItemFile = System.IO.File.Create(driveItemPath))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.CopyTo(driveItemFile);
                }
            }
            await DisplayAlert("Download", selectedFile.DriveItem.Name + " successfully downloaded", "OK");
        }
        catch (Exception ex)
        {
            Console.WriteLine("DOWNLOAD FAILED WITH: " + ex.Message);
            await DisplayAlert("ERROR", selectedFile.DriveItem.Name + " failed with: " + ex.Message, "OK");
        }
    }
}

额外排查建议

如果修复路径后问题仍然存在,可以检查selectedFile.DriveItem.Name是否包含不可见的特殊字符、路径分隔符等非法字符,这类字符会导致路径解析和文件操作异常。

内容的提问来源于stack exchange,提问作者dot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:45:06