简体   繁体   English

Windows XP下的程序路径(C#程序)

[英]Program path under Windows XP(C# program)

My program works fine on Windows 7/ Vista and most Windows XPs I've tested on. 我的程序在Windows 7 / Vista以及我测试过的大多数Windows XP上运行良好。 I open a file that is 1 directory under the program itself. 我打开一个文件,该文件是程序本身下的1个目录。 It's Administration\\adm.txt (that's exactly the relative directory that I use) . 它是Administration \\ adm.txt(这正是我使用的相对目录)。 I am using .NET 2.0 for my project. 我正在为我的项目使用.NET 2.0。 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. 我试图在旧的Windows XP(安装了.NET 2.0)上运行我的程序,我得到了我生命中见过的最奇怪的错误。 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. 因此,如果打开文件对话框上次浏览C:\\ My Documents \\,我尝试打开Administration \\ adm.txt文件,我得到一个例外,“C:\\ My Documents \\ Administration \\ adm.txt”不存在。 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. Windows中的标准行为是文件对话框更改应用程序的当前目录。 You can prevent it with the OFN_NOCHANGEDIR flag to the OPENFILENAME structure that is used to configure the open and save dialogs. 您可以使用OFN_NOCHANGEDIR标志阻止它使用OPENFILENAME 结构 ,该结构用于配置打开保存对话框。

For the story, see the Old New Thing blog: 有关故事,请参阅Old New Thing博客:

http://blogs.msdn.com/b/oldnewthing/archive/2010/11/12/10089878.aspx 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. 除了tinman的回复,我还要补充一点,使用与当前目录相关的目录并不是一个好主意,因为其他进程(包括您自己的进程)可以更改当前目录。 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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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