Why the current working directory changes when use the Open file dialog in Windows XP?

泄露秘密 提交于 2020-01-01 07:37:19

问题


I have found an strange behavior when use the open file dialog in c#.

If use this code in Windows XP the current working directory changes to the path of the selected file, however if you run this code in Windows 7 the current working directory does not change.

    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);
    }

Anybody know the reason for this behavior? Why the current directory changes in XP and not in Windows 7?


回答1:


Based on your description it sounds like the default value of the RestoreDirectory property is different between XP and Windows7. I'm not sure why this would be the case but you can fix this problem by explicitly setting the value in your code. Setting it to true will restore the directory on dialog close.




回答2:


FileDialog (the base class of OpenFileDialog) has a property called AutoUpgradeEnabled which controls whether the dialog takes advantage of the newer file dialogs that were implmented in Vista and newer operating systems when they are available. (Internally this is the difference between calling GetOpenFileName in comdlg32 or in using the IFileDialog interface).

The reason for doing this is that the newer dialogs support a number of features like the "places" bar (see the CustomPlaces collection). An unexpected side effect of this is that the newer IFileDialog implementation does not change the current directory whereas the older version did.

This is a bug in the file dialog implementation and happens regardless of the value of the RestoreDirectory property

If you don't want to use the newer file dialog functionality, the easiest thing to do is to set the AutoUpgradeEnabled to false.



来源:https://stackoverflow.com/questions/3018970/why-the-current-working-directory-changes-when-use-the-open-file-dialog-in-windo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!