Select a file with OpenFileDialog

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
C# Code Snippets

C# Source Code Bank

See also …
edit

This C# code snippet allows the user to pick a file using the OpenFileDialog dialog box.

using System.IO;
using System.Text; 
using System.Windows.Forms;
...
private string SelectTextFile ( string initialDirectory )
{ 
   OpenFileDialog dialog = new OpenFileDialog(); 
   dialog.Filter = 
      "txt files (*.txt)|*.txt|All files (*.*)|*.*"; 
   dialog.InitialDirectory = initialDirectory; 
   dialog.Title = "Select a text file"; 
   return ( dialog.ShowDialog() == DialogResult.OK )
      ? dialog.FileName : null;
}

Personal tools