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
298 views
in Technique[技术] by (71.8m points)

.net - What's the best way to get the directory from which an assembly is executing

For my apps, I store some configuration file in xml along with the assembly(exe), and something other temporary files for proccessing purpose.

I found some quirk with "." and Application.StartupPath.

I've been using

String configPath = ".\config.xml";

It works fine until I called OpenFIleDialog to open some files in other folders, the statement above failed. Apparently "." is referring to "CurrentDirectory", which changes every time when we browse to another folder.

At some point, I was using

String configPath = Path.Combine(Application.StartupPath + "config.xml");

At some point, when I need to execute this assembly from another folder by using Process.Start(), things start to fall apart. Apparently the working directory is not set properly, and Application.StartupPath is actually referring to working directory instead of the directory of which the assembly is executing, as I've assumed. So I have to resort to using ProcessInfo to setup the working directory to the assembly's directory. I also had problem with this when I was writing VSTO.

So, my question is, what's the best, simplest and most assured way to get the current directory that the assembly is executing, without those quirks(or misunderstanding) that I've just mentioned?

EDIT: I meant to get the directory which the assembly reside

EDIT: According to MSDN on AppDomain.BaseDirectory, it seems that it can be changes during runtime, which is what I don't want(Just to clarify, not that I don't want to allow changing BaseDirectory, but rather, when I retrieve it without knowing for sure whether it's been changed)

EDIT: I've notice that a related question was posted much earlier. What would cause the current directory of an executing app to change?

Thanks guys for the answer.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))

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

...