Search code examples
c#file-uploaduwppermission-deniedimgur

Upload an image onto Imgur API - C# UWP


I've been trying to get uploading an image anonymously onto Imgur using the Imgur API to work, however I've been facing an issue with unauthorized path access.

I've tried search around other similar articles on Microsoft Docs and posts here on stack overflow but couldn't find a solution. I've even given my application "broadFileSystemAccess" as rescap capability in my Package.appxmanifest which I found from reading the Microsoft UWP documentations.

The error I receive is:

System.UnauthorizedAccessException: 'Access to the path 'C:\Users\lysyr\Pictures\ROG Logo.png' is denied.'

The error occurs at the var filecon = File.ReadAllBytes(imgpath); line.

My File Picker code is:

public static string imgpath = "";

    public static string finalimg = "";

    private async void FileNameButton_Click(object sender, RoutedEventArgs e)
    {
        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");

        Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
        if (file != null)
        {
            // Application now has read/write access to the picked file
            imgpath = file.Path;
            var filecon = File.ReadAllBytes(imgpath); #Error drops here <---
            finalimg = Convert.ToBase64String(filecon);

            await ImgurUploadAPI();
            Debug.WriteLine("Picked Image: " + file.Name);
            uploadedimage_text.Text = "Picked Image: " + file.Name;
        }
        else
        {
            Debug.WriteLine("Image uploading has been cancelled.");
        }
    }

And the ImgurUpload task code is:

public static string imgurlink = "";

    public async Task ImgurUploadAPI()
    {
        try
        {
            if (imgpath != null)
            {
                // Construct the HttpClient and Uri
                HttpClient httpClient = new HttpClient();
                Uri uri = new Uri("https://api.imgur.com/3/upload");

                httpClient.DefaultRequestHeaders.Add("Authorization", "Client-ID IMGUR-CLIENTIDHERE");
                //Debug.WriteLine("Request Headers: ");

                // Construct the JSON to post
                HttpStringContent content = new HttpStringContent("image=\"{finalimg}\"");
                Debug.WriteLine("Request Upload: " + content);

                // Post the JSON and wait for a response
                HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
                    uri,
                    content);

                // Make sure the post succeeded, and write out the response
                httpResponseMessage.EnsureSuccessStatusCode();
                var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
                imgurlink = httpResponseBody;
                Debug.WriteLine("Request Response: " + httpResponseBody);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
    }

I feel like it might be something to do with the way I access and convert the image to be ready for upload. Any tips would be very appreciated as I've been stuck on this for awhile now and it's one of the last things I need to complete for my project. Cheers!


Solution

  • When you use UWP your access to the file system is limited. This means that you can't simply read a file at an arbitrary path like you're trying to do here:

    var filecon = File.ReadAllBytes(imgpath);
    

    What you need to do instead is to ask the StorageFile object you received from the FilePicker for a read Stream. Like so:

    var buffer = await FileIO.ReadBufferAsync(file);
    var filecon = buffer.ToArray();
    finalimg = Convert.ToBase64String(filecon);
    

    You can find more information about file access for UWP at Microsoft Docs.