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:

  1. using Windows.Storage;     
  2. using Windows.Storage.Pickers;     
  3. using Windows.Storage.Streams;     
  4. using Windows.UI.Xaml;     
  5. using Windows.UI.Xaml.Controls;     
  6. 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: 

  1. <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"/>     
  2. <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:

  1. private async void Add_image(object sender, RoutedEventArgs e)   
  2. {  
  3.     FileOpenPicker fp = new FileOpenPicker(); // Adding filters for the file type to access.         
  4.     fp.FileTypeFilter.Add(".jpeg");  
  5.     fp.FileTypeFilter.Add(".png");  
  6.     fp.FileTypeFilter.Add(".bmp");  
  7.     fp.FileTypeFilter.Add(".jpg");  
  8.     // Using PickSingleFileAsync() will return a storage file which can be saved into an object of storage file class.          
  9.     StorageFile sf = await fp.PickSingleFileAsync();  
  10.     // Adding bitmap image object to store the stream provided by the object of StorageFile defined above.BitmapImage bmp = new BitmapImage();           
  11.     // Reading file as a stream and saving it in an object of IRandomAccess.         
  12.     IRandomAccessStream stream = await sf.OpenAsync(FileAccessMode.Read);  
  13.     // Adding stream as source of the bitmap image object defined above         
  14.     bmp.SetSource(stream);  
  15.     // Adding bmp as the source of the image in the XAML file of the document.         
  16.     image.Source = bmp;  
  17. }  
Run the program created above and enjoy! 
Ebook Download
View all
Learn
View all