views:

719

answers:

3

I'm using a streamwriter to log errors

the way it has been designed (please dont ask why) is to open a new streamwriter everytime the application has to log a message. It outputs everything to ./Logs/[current-date].txt which usually resolves to "c:\myappfolder\logs[current-date].txt"

Everything works correctly, but after I use an open file dialog to say, "C:\home\myfolder\myfile" the streamwriter tries to write to "c:\home\myfolder\logs[current-date].txt"

I know solutions to this problem but i just dont understand what's going on

+9  A: 

The current directory is a process wide value.

The OpenFileDialog is changing the current directory.

If you're using the .NET OpenFileDialog class, you can set the RestoreDirectory property to true to tell the dialog to leave the current directory alone (although the way the docs for RestoreDirectory is written there may be some threading issues, which I imagine might make this still inappropriate for a logging facility).

Michael Burr
Good point regarding thread issues. I assume for logging purposes, this directory is fixed for each run. Saving this to a variable up from is probably the trick then.
biozinc
+3  A: 

As Mike B said, OpenFileDialog may change current directory. Since ./ is relative to current, that changes too.

The RestoreDirectory property modifies this behavior.

Do something like this rather:

OpenFileDialog openFileDialog1 = new OpenFileDialog();

OpenFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;

Taken from MSDN.

biozinc
+2  A: 

Mike B is absolutely correct.

If you're using the native API rather than .NET, you need to set the OFN_NOCHANGEDIR option in the OPENFILENAME structure. The documentation states that it doesn't work for Windows XP though, not sure if this applies to the .NET version or not.

No matter how you fix this, be aware that every time the file dialog opens it will open back in your original folder. If you open lots of files, the cure may be worse than the disease. You may be better off getting the current directory when the program starts, and prepending it to your filenames.

Mark Ransom
Does setting InitialDirectory help with regard to this? I can't remember. The whole notion of current directory is a bit outmoded outside the realm of command line programmes I guess.
biozinc
Setting InitialDirectory will specify which directory will open when the dialog comes up, but I'm not sure if you can get the proper value to plug into it when you use the restore directory option.
Mark Ransom