To select a file using OpenFileDialog in C# and VB.NET you can use the following snippet.

Sample C#

private string SelectFileDialog(string initialDirectory=@"C:\")
	using (var dialog = new OpenFileDialog())
		dialog.Filter = @"All files (*.*)|*.*";
		dialog.InitialDirectory = initialDirectory;
		dialog.Title = @"Select a file";
		return (dialog.ShowDialog() == DialogResult.OK) ? dialog.FileName : string.Empty;

Sample VB.NET

Private Function SelectFileDialog(Optional initialDirectory As String = "C:\") As String
	Using dialog = New OpenFileDialog()
		dialog.Filter = "All files (*.*)|*.*"
		dialog.InitialDirectory = initialDirectory
		dialog.Title = "Select a file"
		Return If((dialog.ShowDialog() = DialogResult.OK), dialog.FileName, String.Empty)
	End Using
End Function

One thought on “How to select a file using OpenFileDialog in C# and VB.NET”

Leave a Reply