简体   繁体   中英

Program path under Windows XP(C# program)

My program works fine on Windows 7/ Vista and most Windows XPs I've tested on. I open a file that is 1 directory under the program itself. It's Administration\\adm.txt (that's exactly the relative directory that I use) . I am using .NET 2.0 for my project. I tried to run my program on an old Windows XP(which had .NET 2.0 installed) and I got the strangest error I have ever seen in my life. The program runs fine, until the user opens an open file dialog. Afterwards the program started thinking that it was in the directory where the open file dialog last was. So if the open file dialog was last browsing through C:\\My Documents\\ and I try to open the Administration\\adm.txt file I get an exception that "C:\\My Documents\\Administration\\adm.txt" does not exist. Unfortunately I can't use that computer myself again, but I'd really like to know how this happened. Does anybody have any ideas?

Standard behaviour in Windows is for the file dialogs to change the application's current directory. You can prevent it with the OFN_NOCHANGEDIR flag to the OPENFILENAME structure that is used to configure the open and save dialogs.

For the story, see the Old New Thing blog:

http://blogs.msdn.com/b/oldnewthing/archive/2010/11/12/10089878.aspx

As well as tinman's reply, I will add that it is not a good idea to use a directory that is relative to the current directory, because other processes (including your own as you have seen) can change the current directory. The following code is a more reliable method to create a file name in a directory below your program's directory:

string exeDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string fileName = System.IO.Path.Combine(exeDirectory, System.IO.Path.Combine("Administration", "adm.txt"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM