The FileOpenPicker is used to select and open files in a Windows Store app. In this article, I will demonstrate how to use the FileOpenPicker class to browse, select and view files.
Step 1.
Create a Windows Store App using Visual Studio 2013.
Step 2.
Double-click on the MainPage.xaml to create your UI.
Add a Button, a TextBlock and an Image control to the page. Change the Name properties of these controls. For example, I changed the Name property of the Button control to FileNameButton and the Image control Name property to ImageViewer.
The final UI looks like Figure 1.
Figure 1.
Step 3.
We will be using some files defined in the following namespace.
Hit F7 while you are on MainPage.xaml in the designer.
Let's add the following namespaces after other namespace definitions at the top of the MainPage's code behind file.
- using Windows.Storage.Pickers;
- using Windows.Storage;
- using Windows.UI.Xaml.Media.Imaging;
Step 4.
Now let's create a button click event handler. Select Button control and open the Properties Windows and find the Click property and double-click on it. It will add the click event handler to the code behind.
Now one more thing I will change is to add “Async” to the click event handler. The final definition looks like the following:
- private async void OpenFileButton_Click(object sender, RoutedEventArgs e)
Now, let's use the FileOpenPicker to browse and open a file. The complete code is listed in Listing 1. The code is very self-explanatory. I set the starting location and file filters then open a stream that is later used to create a BitmapImage.
- private async void OpenFileButton_Click(object sender, RoutedEventArgs e)
- {
-
- FileOpenPicker fileOpenPicker = new FileOpenPicker();
-
-
- fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
-
-
- fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
-
-
-
-
- fileOpenPicker.FileTypeFilter.Clear();
- fileOpenPicker.FileTypeFilter.Add(".png");
- fileOpenPicker.FileTypeFilter.Add(".jpeg");
- fileOpenPicker.FileTypeFilter.Add(".jpg");
- fileOpenPicker.FileTypeFilter.Add(".bmp");
-
-
- StorageFile file = await fileOpenPicker.PickSingleFileAsync();
- if (file != null)
- {
- FileNameTextBlock.Text = file.Name;
-
- Windows.Storage.Streams.IRandomAccessStream fileStream =
- await file.OpenAsync(FileAccessMode.Read);
-
-
- BitmapImage bitmapImage = new BitmapImage();
- bitmapImage.SetSource(fileStream);
-
-
- ImageViewer.Source = bitmapImage;
- }
- }
Step 5.
If hit F5 to run your app. Click on the Open File button and you can see the images in the defined folder are displayed. Select an image and click the Open button.
The output looks like Figure 2.
Figure 2.