Why the current working directory changes when use

2019-04-03 11:44发布

问题:

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.