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();
- fp.FileTypeFilter.Add(".jpeg");
- fp.FileTypeFilter.Add(".png");
- fp.FileTypeFilter.Add(".bmp");
- fp.FileTypeFilter.Add(".jpg");
-
- StorageFile sf = await fp.PickSingleFileAsync();
-
-
- IRandomAccessStream stream = await sf.OpenAsync(FileAccessMode.Read);
-
- bmp.SetSource(stream);
-
- image.Source = bmp;
- }
Run the program created above and enjoy!