OpenFileDialog in C#

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.

    private void btnOpenTextFile_Click(object sender, EventArgs e)


First, declare a variable to hold the user's file selection.

            String input = string.Empty;


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.

            OpenFileDialog dialog = new OpenFileDialog();


Now we set the file type we want to be available to the user.  In this case, text files.


            dialog.Filter =

               "txt files (*.txt)|*.txt|All files (*.*)|*.*";


            Next is the starting directory for the dialog and the title for the dialog box are set.

dialog.InitialDirectory = "C:";

            dialog.Title = "Select a text file";


Once the dialog properties are set, it is ready to present to the user.

            if (dialog.ShowDialog() == DialogResult.OK)

                strFileName =  dialog.FileName;

            if (strFileName == String.Empty)

                return; //user didn't select a file to opena

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.




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


Similar Articles