C#中的OpenFileDialog

4 c# label dialog winforms

如何从打开文件对话框中获取结果(表示文件名及其位置)?

我的代码:

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

Lar*_*ech 5

OpenFileDialog类具有FileName属性.

通常,您希望确保用户没有取消对话框:

using (var selectFileDialog = new OpenFileDialog()) {
  if (selectFileDialog.ShowDialog() == DialogResult.OK) {
    fileName.Text = selectFileDialog.FileName;
  }
}
Run Code Online (Sandbox Code Playgroud)


sll*_*sll 5

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)