简体   繁体   中英

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

I'm developing a uwp platform that permit to upload image to imgur with the imgur api. I'm doing this :

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);
            }

I have this error :

  • $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, FileAcc ess 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

I tried to create a new directory in C:/ folder with my picture, change security rights, execute Visual studio as administrator but nothing changed...

The error happens on var fs = new FileStream(@path, FileMode.Open, FileAccess.Read, FileShare.Read

I've seen many topics about this all the day i've tried everything but nothing change if someone have any idea !

When user selects an arbitrary file using FileOpenPicker , you get a StorageFile instance. This is the only way you can access the file, you cannot use the Path directly, as that API is not under the WinRT sandbox. You can access only files in your app's AppData directory directly with Path .

You can however get a stream from the retrieved StorageFile bu calling the appropriate extension method:

var stream = await file.OpenStreamForReadAsync();

Update

Information in this post is now outdated. 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. This capability is however checked during certification so you have to make sure the app has a good reason to have access to all of the user's filesystem, because your app will be rejected otherwise, to prevent malicious misuse.

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.

NO It does not

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 works OK, but System.IO have a System.UnauthorizedAccessException: 'Access to the path 'C:\\1\\1.txt' is denied.'

According to the Microsoft Docs, UWP apps are sandboxed, meaning (unlike a console app) they have limited access to the computer's resources. It is possible to grant additional capabilities to a UWP app by modifying the Package.appxmanifest .

These links have the full story:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM