OpenFileDialog In C#

The OpenFileDialog object interacts with the Computer’s API (Application Programming Interface) to present available files to the user and retrieves the user’s file selection back to the program.

Opening and Reading a Text File using the OpenFileDialog form in C#.NET

The OpenFileDialog object interacts with the Computer's API (Application Programming Interface) to present available files to the user and retrieves the user's file selection back to the program. This object is part of the System.Windows.Forms library so no additional using reference will be needed.

This dialog can be customized to show the file type, beginning directory, and the title to be displayed on the dialog itself.

When you limit the file type to just the extension .txt as we did in this sample code, only those particular file types will be visible to the user although they do have the option to select All files (*) as well.

Let's review the function below (a button click event in this example) that is used to interact with this OpenFileDialog.

  1. privatevoid btnOpenTextFile_Click(object sender, EventArgs e) {  
  2.     //First, declare a variable to hold the user's file selection.  
  3.     String input = string.Empty;  
  4.     //Because the OpenFileDialog is an object, we create a new instance by declaring a variable with the data type OpenFileDialog and setting it equal to the new instance.  
  5.     OpenFileDialog dialog = newOpenFileDialog();  
  6.     //Now we set the file type we want to be available to the user. In this case, text files.  
  7.     dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";  
  8.     //Next is the starting directory for the dialog and the title for the dialog box are set.  
  9.     dialog.InitialDirectory = "C:";  
  10.     dialog.Title = "Select a text file";  
  11.     //Once the dialog properties are set, it is ready to present to the user.  
  12.     if (dialog.ShowDialog() == DialogResult.OK) strFileName = dialog.FileName;  
  13.     if (strFileName == String.Empty) return//user didn't select a file to opena  
  14.     //If the user selected a file, then the DialogResult property value will be "OK" and we will also have the file name and path of that file.  
  15. }  

 

Now we can use the StreamWriter and StreamReader to read/write to the text file