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.
- privatevoid btnOpenTextFile_Click(object sender, EventArgs e) {
-
- String input = string.Empty;
-
- OpenFileDialog dialog = newOpenFileDialog();
-
- dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
-
- dialog.InitialDirectory = "C:";
- dialog.Title = "Select a text file";
-
- if (dialog.ShowDialog() == DialogResult.OK) strFileName = dialog.FileName;
- if (strFileName == String.Empty) return;
-
- }
Now we can use the StreamWriter and StreamReader to read/write to the text file