OpenFileDialog只选择文件路径

时间:2015-02-13 20:44:46

标签: c#

我正在尝试使用OpenFileDialog让用户选择可以与我的应用互动的本地文件。当用户选择该文件时,该文件可以正在使用,因为我真的只想获取文件的路径。我的问题是,如果我尝试使用OpenFileDialog执行此操作,当用户按下"打开"时,它实际上会尝试打开文件,即使我不打算在任何地方打开。由于文件正在使用中,因此会抛出错误。

我有没有办法为用户提供一个对话框选择一个文件而不做其他事情?

继承我目前的代码:

        DialogResult result = this.qbFilePicker.ShowDialog();
        if (result == DialogResult.OK)
        {
            string fileName = this.qbFilePicker.FileName;
            Console.WriteLine(fileName);
        }

1 个答案:

答案 0 :(得分:1)

确保您正在使用

using System.Windows.Forms;

然后,MSDN中的以下代码将不会打开您的文件,除非您明确取消注释打开该文件的位:)

(取出与你不相关的内容,例如.txt过滤器等)

 private void Button_Click(object sender, RoutedEventArgs e)
 {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.InitialDirectory = "c:\\";
        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;

        if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string fileName = openFileDialog1.FileName;
            Console.WriteLine(fileName);

            //to open the file
            /*
            try
            {
                Stream myStream = null;
                if ((myStream = openFileDialog1.OpenFile()) != null)
                {
                    using (myStream)
                    {
                        // Insert code to read the stream here.
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
             * */
        }
}
相关问题