【问题标题】:Why the current working directory changes when use the Open file dialog in Windows XP?为什么在 Windows XP 中使用打开文件对话框时当前工作目录会发生变化?
【发布时间】:2010-06-10 22:22:12
【问题描述】:

我在 c# 中使用打开文件对话框时发现了一个奇怪的行为。

如果在Windows XP 中使用此代码,则当前工作目录会更改为所选文件的路径,但是如果您在Windows 7 中运行此代码,则当前工作目录不会更改。

    private void button1_Click(object sender, EventArgs e)
    {            
        MessageBox.Show(string.Format("Current Directory {0}",Directory.GetCurrentDirectory()), "My Application",MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog and get result.
        if (result == DialogResult.OK) 
        {

        }
        MessageBox.Show(string.Format("Current Directory {0}", Directory.GetCurrentDirectory()), "My Application", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
    }

有人知道这种行为的原因吗?为什么当前目录在 XP 而不是 Windows 7 中更改?

【问题讨论】:

    标签: c# .net openfiledialog


    【解决方案1】:

    根据您的描述,RestoreDirectory 属性的默认值似乎在 XP 和 Windows7 之间有所不同。我不确定为什么会出现这种情况,但您可以通过在代码中显式设置值来解决此问题。将其设置为 true 将在对话框关闭时恢复目录。

    【讨论】:

    • 谢谢你的回答我真的知道如何解决这个问题。我只是想知道这种行为的原因。
    • @RRUZ,我自己也很好奇。挖掘反射器中的代码,我看到了一种特殊的 Vista 方法(HandleVistaFileOK)。我怀疑这种方法是负责任的,但它又一次没有真正回答为什么的问题。
    【解决方案2】:

    FileDialog(OpenFileDialog 的基类)有一个名为 AutoUpgradeEnabled 的属性,它控制对话框是否利用在 Vista 和更新的操作系统中实现的更新文件对话框(当它们可用时)。 (在内部,这是在 comdlg32 中调用 GetOpenFileName 或在使用 IFileDialog 接口时的区别。

    这样做的原因是较新的对话框支持许多功能,例如“地点”栏(请参阅 CustomPlaces 集合)。一个意想不到的副作用是,较新的 IFileDialog 实现不会更改当前目录,而旧版本会更改。

    这是文件对话框实现中的一个错误,无论 RestoreDirectory 属性的值如何都会发生

    如果您不想使用较新的文件对话框功能,最简单的做法是将 AutoUpgradeEnabled 设置为 false。

    【讨论】:

      猜你喜欢
      • 2017-05-05
      • 1970-01-01
      • 2011-02-08
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      相关资源
      最近更新 更多