OpenFileDialog in C#

18,067

Solution 1

private void selectFileButton_Click( object sender, EventArgs e ) 
{
    Stream fileStream = null;
    //Update - remove parenthesis
    if (selectFileDialog.ShowDialog() == DialogResult.OK && (fileStream = selectFileDialog.OpenFile()) != null)
    {
        string fileName = selectFileDialog.FileName;
        using (fileStream)
        {
           // TODO
        }
    }
}

Solution 2

The OpenFileDialog class has a FileName property for that.

Typically, you want to make sure the user didn't cancel the dialog:

using (var selectFileDialog = new OpenFileDialog()) {
  if (selectFileDialog.ShowDialog() == DialogResult.OK) {
    fileName.Text = selectFileDialog.FileName;
  }
}
Share:
18,067
Admin
Author by

Admin

Updated on July 21, 2022

Comments

  • Admin
    Admin almost 2 years

    How can I get the result (meaning the file name and its location) from an Open File Dialog?

    My code:

    private void selectFileButton_Click( object sender, EventArgs e ) {
        var selectedFile = selectFileDialog.ShowDialog();
        //label name = fileName
        fileName.Text = //the result from selectedFileDialog
    }