In Windows 10 we have OpenFileDialog which opens a dialog to pick the files. Here we are going to pick the text file in Windows 10.
Create new Windows 10 project and create a button and image control to perform File Picker operation.
Firstly, create a new instance for FileOpenPicker as in the following code snippet:
- FileOpenPicker openPicker = new FileOpenPicker();
Next, we have to set file picker ViewMode, you could ignore this, but if you would like to add, there are two options, such as List and Thumbnail. Here I will set thumbnail.
- openPicker.ViewMode = PickerViewMode.Thumbnail;
Then set the suggested location as you wish. I am going to set default location as document library.
- openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
We need to add FileTypeFilter; it is a mandatory field that you should add. It requires at least one type.
The FileTypeFilter is a readonly collection. We would be able to add values.
Here I am setting filter type for .txt files.
- openPicker.FileTypeFilter.Add(".txt");
Finally, we are going to show the file picker dialog as in the following code snippet and we have the option to select single or multiple file selection.
- StorageFile file = await openPicker.PickSingleFileAsync();
Finally, we are going to read the selected file using stream and assign it to textblock.
- var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
- using (StreamReader reader = new StreamReader(stream.AsStream()))
- {
- textBlockShow.Text = reader.ReadToEnd();
- }
The whole code looks like the following code:
- private async void buttonPick_Click(object sender, RoutedEventArgs e)
- {
- FileOpenPicker openPicker = new FileOpenPicker();
- openPicker.ViewMode = PickerViewMode.Thumbnail;
- openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
- openPicker.FileTypeFilter.Add(".txt");
- StorageFile file = await openPicker.PickSingleFileAsync();
- if(file != null)
- {
- var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
- using(StreamReader reader = new StreamReader(stream.AsStream()))
- {
- textBlockShow.Text = reader.ReadToEnd();
- }
- }
- else
- {}
- }
Now run, debug and run the app and here is the following output,