CODEDIGEST InstallShield
Home Articles CodeDigest Tutorials InstallShield FAQs
Skip Navigation LinksHome » Article » Csharp Article » How to call the Windows API FileOpen Dialog  Submit Articles and Win Geeky Prizes!!   You are not logged in.
Search
 

Sponsors
InstallShield
 

Product Spotlight
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
How to Open File Dialog in C#
Free Trial: InstallShield 2010 for Windows Installers Is InstallShield right for you? InstallShield handles your most complex installation requirements in minutes. Try it now.

By Tamara Urry
Posted On Jun 26,2009
Article Rating: (Login)
Be first to rate
this article.
No of Comments: 0
Category: C#
Print this article.

Subscribe to our feed!

How to Open File Dialog 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. This object is part of the System.Windows.Forms library so no additional using reference will be needed.

This example uses a button click method.

private void btnOpenTextFile_Click(object sender, EventArgs e)

{

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

private void String input = string.Empty;

 

//Create a new instance of the OpenFileDialog because it's an object.

private voidOpenFileDialog dialog = new OpenFileDialog();

 

//Now set the file type

dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

 

//Set the starting directory and the title.

dialog.InitialDirectory = "C:"; dialog.Title = "Select a text file";

 

//Present to the user.

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

     strFileName = dialog.FileName;

if (strFileName == String.Empty)

     return;//user didn't select a file

}

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.