tags:

views:

23

answers:

2

say my application is installed in C:\programfiles\xyz\ I've some setting & other data files (*.dat files) in this directory too.

My application uses OpenFileDialog to open an image. Problem is that when ever user browses to some directory (say MyPictures) for an image. The current working directory of the application becomes that directory (MyPictures in this case).

After user inputs the image. I do some processing over it and save some values to imagedata.dat which will be located in the path where original application is installed.(C:\programfiles\xyz here )

In my code I'm just using FileStream("imagedata.dat",...,...) without any path prefix before the filename. Problem here is that application is crashing because it is searching for imagedata.dat in 'MyPictures\imagedata.dat'.

How can I avoid this?

A: 

You could save it to GetCurrentDirectory then restore with SetCurrentDirectory. However, I agree wih codeka that using the appropriate GetFolderPath (probably ApplicationData, CommonApplicationData or LocalApplicationData) is a better solution.

Matthew Flaschen
+3  A: 

You should be using absolute path names when saving data to files. The current working directory is controlled by the user, not by you (for example, if they launch your process from a shortcut then the working directory could've been changed before your process even starts up).

Also, you should never save anything under C:\Program Files during normal use. Doing this means your program needs to be running as an administrator, and unless you're doing administrator-y things then you should be able to run it as a regular user.

The correct thing to do in your case is to use the Environment.GetFolderPath() function to get the location of the ApplicationData folder and save your data under there. Just choose a sub-directory based on your application's name.

Dean Harding
is it ApplicationData or LocalApplicationData?
pecker
@pecker Either should work. I believe the difference is that LocalApplicationData stays on that PC, and isn't part of the user's roaming profile.
Andy