Introduction
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 a 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 the default location as a 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 read-only 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 a stream and assign it to the text block.
- 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,
Summary
In this article, we learned about how to pick the text files in Windows 10.