如何从打开文件对话框中获取结果(即文件名及其位置)?
我的代码:
private void selectFileButton_Click( object sender, EventArgs e ) {
var selectedFile = selectFileDialog.ShowDialog();
//label name = fileName
fileName.Text = //the result from selectedFileDialog
}
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
}
}
}
OpenFileDialog 类有一个 FileName 属性。
通常,您要确保用户没有取消对话框:
using (var selectFileDialog = new OpenFileDialog()) {
if (selectFileDialog.ShowDialog() == DialogResult.OK) {
fileName.Text = selectFileDialog.FileName;
}
}
if(selectFileDialog.ShowDialog())
{
// use the methods and properties on selectFileDialog
fileName.Text = selectFileDialog.FileName; // Assumes only one file was selected
}
您可以尝试使用此代码
if(selectFileDialog.ShowDialog() == DialogResult.OK)
{
var result = selectFileDialog.FileName;
if((myStream = selectFileDialog.OpenFile())!= null)
{
// Insert code to read the stream here.
..........
myStream.Close();
}
}