OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; // Code to do something with the selected file } openFileDialog.Dispose();
private void btnSelectFile_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; // Code to do something with the selected file } } }This example shows how to use the OpenFileDialog with a button click event. The using statement is used to automatically dispose of the dialog box object after its use. If the user clicks the OK button, the selected file path is retrieved and can be used in the application. Package Library: The OpenFileDialog class is a part of the System.Windows.Forms namespace and is built into the .NET Framework. No external package or library is required to use it.