Search code examples
c#visual-studioassetswindows-10-universalfilepicker

Add an image to assets on runtime c# (uwp)


I am trying to make an add image function. Where the user can upload a picture of an item, and it will add that picture to my project's assets for future use. this is my code :

private async void PickAFileButton_ClickAsync(object sender, RoutedEventArgs e)
    {
        FileOpenPicker openPicker = new FileOpenPicker();
        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        openPicker.FileTypeFilter.Add(".jpg");
        openPicker.FileTypeFilter.Add(".jpeg");
        openPicker.FileTypeFilter.Add(".png");

        StorageFile file = await openPicker.PickSingleFileAsync();
        if (file != null)
        {
            // Application now has read/write access to the picked file
            String a = "ms-appx:///Assets/" + file.Name;
            theItem.Source = new BitmapImage(new Uri(a));
        }
        else
        {
            theImage.Text = "Operation cancelled.";
        }
    }

How do I Add the given picture to my project's assets folder so that I could show it at the side, and use it for other things as well?

I will be very grateful for any help.


Solution

  • How do I Add the given picture to my project's assets folder

    The assets folder of the uwp project is read only in run time model, we could not add the picture in run time. We suggest to use Local folder to replace Assets folder.

    private async void PickAFileButton_ClickAsync(object sender, RoutedEventArgs e)
    {
        FileOpenPicker openPicker = new FileOpenPicker();
        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        openPicker.FileTypeFilter.Add(".jpg");
        openPicker.FileTypeFilter.Add(".jpeg");
        openPicker.FileTypeFilter.Add(".png");
    
        StorageFile file = await openPicker.PickSingleFileAsync();
        if (file != null)
        {   await file.CopyAsync( ApplicationData.Current.LocalFolder );
            // Application now has read/write access to the picked file
            String a = "ms-appdata:///local/" + file.Name;
            theItem.Source = new BitmapImage(new Uri(a));
        }
        else
        {
            theImage.Text = "Operation cancelled.";
        }
    }