System.UnauthorizedAccessException: 路径访问被拒绝 (UWP C#)

System.UnauthorizedAccessException: Access to the path is denied (UWP C#)

我正在开发一个允许使用 imgur api 将图像上传到 imgur 的 uwp 平台。 我正在这样做:

var picker = new Windows.Storage.Pickers.FileOpenPicker();
        picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation =
            Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
        picker.FileTypeFilter.Add(".jpg");
        picker.FileTypeFilter.Add(".jpeg");
        picker.FileTypeFilter.Add(".png");
        String path;

        Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
        if (file != null)
        {
            path = file.Path;
        }
        else
        {
            path = "Operation cancelled.";
        }
try
            {
                var client = new ImgurClient("id", "secret");
                var endpoint = new ImageEndpoint(client);
                IImage img;
            await Task.Run(async () =>
            {
                await Task.Yield();
                Debug.Write("crash at FileStream\n");
                using (var fs = new FileStream(@path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    Debug.Write("crash at Upload\n");
                    img = await endpoint.UploadImageStreamAsync(fs);
                    Debug.Write("Image uploaded. Image Url: " + img.Link);
                    Windows.UI.Xaml.Controls.Image image = new Windows.UI.Xaml.Controls.Image();
                    image.Source = new BitmapImage(new Uri(img.Link));
                    image.Width = img.Width;
                    image.Height = img.Height;
                    imgList.Clear();
                    imgList.Add(image);
                    await LoadGalery();
                    index = 0;
                }
            });
            }
            catch (ImgurException imgurEx)
            {
                Debug.Write("An error occurred uploading an image to Imgur.");
                Debug.Write(imgurEx.Message);
            }

我有这个错误:

  • $exception {System.UnauthorizedAccessException: Access to the path 'C:\Nouveau dossier\mmmh.PNG' is denied. at System.IO.WinRTIOExtensions.d__2`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.IO.WinRTFileSystem.d__41.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.IO.WinRTFileSystem.Open(String fullPath, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, FileStream parent) at System.IO.MultiplexingWin32WinRTFileSystem.Open(String fullPath, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, FileStream parent) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at App1.MainPage.<>c__DisplayClass7_1.<b__0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    at App1.MainPage.d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    at App1.MainPage.d__9.MoveNext()} System.UnauthorizedAccessException

我尝试在 C:/ 文件夹中用我的照片创建一个新目录,更改安全权限,以管理员身份执行 Visual studio 但没有任何改变...

错误发生在 var fs = new FileStream(@path, FileMode.Open, FileAccess.Read, FileShare.Read

我一整天都看到了很多关于这个的话题,我已经尝试了所有的方法,但如果有人有任何想法的话,没有任何改变!

当用户使用 FileOpenPicker 选择任意文件时,您将获得一个 StorageFile 实例。这是访问该文件的唯一方法,不能直接使用 Path,因为 API 不在 WinRT 沙箱下。您只能直接使用 Path.

访问您应用的 AppData 目录中的文件

但是,您可以通过调用适当的扩展方法从检索到的 StorageFile 中获取流:

var stream = await file.OpenStreamForReadAsync();

更新

post 中的信息现已过时。自 2018 年 4 月更新 Windows 10 以来,您可以声明广泛的文件系统访问功能,这将允许您的应用程序访问文件系统中的任何路径,即使使用 System.IO APIs。但是,此功能会在认证期间进行检查,因此您必须确保该应用程序有充分的理由可以访问用户的所有文件系统,否则您的应用程序将被拒绝,以防止恶意滥用。

Since April 2018 update of Windows 10 you can declare a >Broad Filesystem access capability that will allow your app >to access any path in the filesystem even with the >System.IO APIs.

不 不会

StorageFile file = await 
StorageFile.GetFileFromPathAsync("c:\1\1.txt");

//string s = File.ReadAllText("C:\1\1.txt");
//string s = await 
File.ReadAllTextAsync("C:\1\1.txt");

string text = await 
Windows.Storage.FileIO.ReadTextAsync(file);

var dialog = new MessageDialog("done");
await dialog.ShowAsync();

StorageFile 工作正常,但 System.IO 有一个 System.UnauthorizedAccessException:'访问路径 'C:.txt' 被拒绝。'

根据 Microsoft 文档,UWP 应用程序是沙盒化的,这意味着(与控制台应用程序不同)它们对计算机资源的访问权限有限。可以通过修改 Package.appxmanifest.

为 UWP 应用授予额外的功能

这些链接有完整的故事:

https://docs.microsoft.com/en-us/windows/uwp/packaging/app-capability-declarations#custom-capabilities https://docs.microsoft.com/en-us/windows/uwp/files/file-access-permissions