简体   繁体   中英

OpenFileDialog in C#

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
}

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;
  }
}
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
        }
    }
}

This Link may be useful: http://softsprogrammer.blogspot.in/2014/03/openfiledialog-in-c.html

The page shows hot to use OpenFileDialog in a Windows Form.

if(selectFileDialog.ShowDialog())
{
  // use the methods and properties on selectFileDialog
  fileName.Text = selectFileDialog.FileName; // Assumes only one file was selected
}

You can try with this code

if(selectFileDialog.ShowDialog() == DialogResult.OK)
{
        var result = selectFileDialog.FileName; 

        if((myStream = selectFileDialog.OpenFile())!= null)
        {
            // Insert code to read the stream here.
            ..........
            myStream.Close();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM