How To Pick Text File In Windows 10

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:

  1. 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.
  1. openPicker.ViewMode = PickerViewMode.Thumbnail;  
Then set the suggested location as you wish. I am going to set default location as document library.
  1. 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.
  1. 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.
  1. StorageFile file = await openPicker.PickSingleFileAsync();  
Finally, we are going to read the selected file using stream and assign it to textblock.
  1. var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);  
  2. using (StreamReader reader = new StreamReader(stream.AsStream()))  
  3. {  
  4.    textBlockShow.Text = reader.ReadToEnd();  
  5. }  
The whole code looks like the following code:
  1. private async void buttonPick_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     FileOpenPicker openPicker = new FileOpenPicker();  
  4.     openPicker.ViewMode = PickerViewMode.Thumbnail;  
  5.     openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;  
  6.     openPicker.FileTypeFilter.Add(".txt");  
  7.     StorageFile file = await openPicker.PickSingleFileAsync();  
  8.     if(file != null)  
  9.     {  
  10.         var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);  
  11.         using(StreamReader reader = new StreamReader(stream.AsStream()))  
  12.         {  
  13.             textBlockShow.Text = reader.ReadToEnd();  
  14.         }  
  15.     }  
  16.     else  
  17.     {}  
  18. }  
Now run, debug and run the app and here is the following output,

 

output

Open file

Up Next
    Ebook Download
    View all
    Learn
    View all