views:

1044

answers:

3

Why does OpenFileDialog change my working directory? Should i assume many func in System.Windows.Forms will change my working directory?

    OpenFileDialog open = new OpenFileDialog();
    open.Filter = filter;
    a = Directory.GetCurrentDirectory(); //<-- correct
    if (open.ShowDialog() == DialogResult.OK) //-- select a file on my desktop
    {
        a = Directory.GetCurrentDirectory(); //<-- incorrect, is set to my desktop
+5  A: 

The current working directory can change during runtime, yes.

Consider using

Directory.GetParent(Assembly.GetExecutingAssembly().Location)

or

System.AppDomain.CurrentDomain.BaseDirectory

when you need your applications directory.

tanascius
heh, not that easy. I just use get/set when i need to. I use MSVS to set the working directory so theres no possible way for me to detect where it should be (unless i hardcode it into the exe)
acidzombie24
+5  A: 

It is a pain, although in some ways you might anticipate it... if you go into an open dialog multiple times (in an app) you often find it where you last left it.

If it impacts your code, you could take a snapshot of GetCurrentDirectory() before going into the dialog, and restore it afterwards (so your code doesn't see the change). You might want to store the user's working directory separately (and swap them) so that the user also gets their expected behaviour.

Marc Gravell
Thats exactly what i did. It was just surprising to see it happened. I am glad to see you think it is a pain as well.
acidzombie24
+7  A: 

Or you can make it not do that. See the FileDialog.RestoreDirectory property.

Mike