C# OpenFileDialog仅选择文件路径

C# OpenFileDialog仅选择文件路径,c#,C#,我正在尝试使用OpenFileDialog让用户选择一个可以与我的应用程序交互的本地文件。当用户选择该文件时,该文件可以被使用,因为我只想获取该文件的路径。我的问题是,如果我尝试使用OpenFileDialog执行此操作,当用户按“打开”时,它实际上会尝试打开文件,即使我不要求在任何地方打开。由于文件正在使用中,因此会抛出一个错误 我有没有办法为用户提供一个对话框,让用户只选择一个文件而不做其他事情 这是我目前的代码: DialogResult result = this.qbF

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

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

这是我目前的代码:

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

确保您正在使用

using System.Windows.Forms;
然后,除非您显式取消注释打开文件的位,否则MSDN中的以下代码将不会打开您的文件:)

(去掉与您无关的位,如.txt过滤器等)


OpenFileDialog
不会打开文件,它只允许您选择要打开的文件。这里的代码不应该出现异常。我认为OP要求的对话框不显示目录中文件的常规资源管理器上下文菜单,即没有打开、打印、删除、重命名、属性等选项,只是选择文件的方法。如果您只需要一个路径,试着用FolderBrowserDialog来代替。我知道以前有人问过这个问题,但答案是创建自己的对话框。
 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);
            }
             * */
        }
}