File Picker in Windows 10 Universal App

In this post I will start with adding File Picker functionality in Windows 10 universal applications built in C#. Here we are using few libraries to perform the task, before proceeding in the program further, we should add the following namespaces to the .CS file of the Main Window:


using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

Now in the XAML page of the application, we will add a button and an image control to call the method to invoke filepicker and present the selected image file in the image control respectively:


<Button x:Name="button" Content="Add Image" HorizontalAlignment="Left" Margin="497,55,0,0"
VerticalAlignment="Top" Height="58" Width="261" FontSize="33.333" Click="Add_image"/>
<Image x:Name="image" HorizontalAlignment="Left" Height="316"
Margin="396,231,0,0" VerticalAlignment="Top" Width="456"/>

Now, in the .CS file, we will add the File Picker method to find the image and show it in the image control in XAML file defined above. The code to be added in the .CS file is as follows:


private async void Add_image(object sender, RoutedEventArgs e)
{
FileOpenPicker fp = new FileOpenPicker();

// Adding filters for the file type to access.
fp.FileTypeFilter.Add(".jpeg");
fp.FileTypeFilter.Add(".png");
fp.FileTypeFilter.Add(".bmp");
fp.FileTypeFilter.Add(".jpg");

// Using PickSingleFileAsync() will return a storage file which can be saved into an object of storage file class.

StorageFile sf = await fp.PickSingleFileAsync();

// Adding bitmap image object to store the stream provided by the object of StorageFile defined above.
BitmapImage bmp = new BitmapImage();

// Reading file as a stream and saving it in an object of IRandomAccess.
IRandomAccessStream stream = await sf.OpenAsync(FileAccessMode.Read);

// Adding stream as source of the bitmap image object defined above
bmp.SetSource(stream);

// Adding bmp as the source of the image in the XAML file of the document.
image.Source = bmp;
}

Run the program created above and enjoy!