Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

c# - Environment.CurrentDirectory is yielding unexpected results when running installed app

Background:

I built an installer for my app, and all my dll's and content files are getting correctly copied to the C:Program FilesMyCompanyMyApp directory. When I run my app from Visual Studio, everything works great. When I run the installed version of my app, however, I get a DirectoryNotFoundException. The problem seems to be with Environment.CurrentDirectory.

I was expecting Environment.CurrentDirectory to be...

"C:\Program Files\MyCompany\MyApp"

...but it was actually...

"C:\Documents and Settings\DanThMan"

What's going on here? How do I solve this?

Thanks.

EDIT:

Okay, hmm. This problem only occurs if I run the Start Menu shortcut. If I run MyApp.exe directly, everything is fine.

EDIT 2:

I think I've gotten to the bottom of this now. In my Installer (which is a Visual Studio SetupProject), the Start Menu shortcut has a property called WorkingFolder, which "Specifies the folder where the target application for the shortcut will be installed." I had accidentally set WorkingFolder to "MyCompany". It should be "Application Folder". Now that I have it set correctly, Environment.CurrentDirectory is once again working as expected. Thanks for all your help.

EDIT 3:

However, reading the warnings below, I have decided to go with the following as a replacement for Environment.CurrentDirectory:

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to get the path to the directory under which your executable runs, you should not rely on the Environment.CurrentDirectory, since it can be changed in a number of ways (shotrtcut settings, etc). Try one of these options instead:

System.IO.Path.GetDirectoryName(Application.ExecutablePath);

or

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...