ABC Article Directory banner displaying blue butterfly logo. Click to go directly to the main Homepage
Your Ad Here

Home | Computers | Programming

Add This Social Bookmark Button


animated blue butterfly symbol for the ABC Article Directory

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


By: Robert Pattinson Click author's name for more of his/her articles

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

Article Source: ABC Article Directory



About The Author: www.jettechnical.com/openfiledialog.htm



Bookmark and Share eMail This Article to Friends

Please Rate this Article


Not yet Rated



RSS feeds on demand

Copyright ABC Article Directory All rights protected. Script Services by: Sustainable Website Design
Use of our free service is protected by our Privacy Policy and Terms of Service Contact Us
Creative Commons License
This work is licensed under a Creative Commons Attribution-No Derivative Works 3.0 Unported License.

Wind Powered Hosting

Powered by Article Dashboard