.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month

Home >> Code Snippets >> Windows Form Controls >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

OpenFile Dialog Box

Posted By:Deepika Haridas       Posted Date: September 26, 2009    Points: 10    Category: Windows Form Controls    URL: http://www.dotnetspark.com  

OpenFile Dialog Box to select a file. For a wrong input (filename) it will show a error message.

private void btnOpenTextFile_Click(object sender, System.EventArgs e)
StreamReader ts = null;
odlgTextFile.CheckFileExists = true;

// Check to ensure that the selected
// path exists. Dialog box displays
// a warning otherwise.

odlgTextFile.CheckPathExists = true;

odlgTextFile.DefaultExt = "txt";

// return the file referenced by a link? if
// false, simply returns the selected link
// file. if true, returns the file linked to
// the LNK file.

odlgTextFile.DereferenceLinks = true;

// Just in VB6, use a set of pairs
// of filters, separated with "|". Each
// pair consists of a description|file spec.
// Use a "|" between pairs. No need to put a
// trailing "|". You can set the FilterIndex
// property well, to select the default
// filter. Amazingly, the first filter is
// numbered 1 (! 0). The default is 1.

odlgTextFile.Filter = "Text files (*.txt)|*.txt|" + "All files|*.*";

odlgTextFile.Multiselect = false;

// Restore the original directory when done selecting
// a file? if false, the current directory changes
// to the directory in which you selected the file.
// Set this to true to put the current folder back
// where it was when you started.
// The default is false.

odlgTextFile.RestoreDirectory = true;

// Show the Help button and Read-Only checkbox?

odlgTextFile.ShowHelp = true;

odlgTextFile.ShowReadOnly = false;

// Start out with the read-only check box checked?
// This only make sense if ShowReadOnly is true.
// .ReadOnlyChecked = false

odlgTextFile.Title = "Select a file to open";

// Only accept valid Win32 file names?

odlgTextFile.ValidateNames = true;

if (odlgTextFile.ShowDialog() == DialogResult.OK)
FileName = odlgTextFile.FileName;
ts = new StreamReader(odlgTextFile.OpenFile());
txtFileContents.Text = ts.ReadToEnd();
catch (Exception exp)
MessageBox.Show(exp.Message, this.Text);
if(ts != null)


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend