看一下这个伪代码:
string exe_path = system.get_exe_path()
print "This executable is located in " + exe_path
如果我构建上述程序并将可执行文件放在中C:/meow/
,This executable is located in C:/meow/
则无论当前工作目录如何,每次运行时它都会打印出。
我如何轻松地使用来完成此操作C#
?
MSDN上有一篇文章说要使用System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
;如果需要目录,请使用System.IO.Path.GetDirectoryName
该结果。
或者,缩写Application.ExecutablePath
为“获取启动应用程序的可执行文件的路径,包括可执行文件的名称”,这可能意味着它的可靠性稍差,具体取决于应用程序的启动方式。
System.Reflection.Assembly.GetExecutingAssembly()仅在从那里调用EXE程序集的情况下才会获得。GetEntryAssembly()将获取正确的程序集。
如果您创建Windows服务,这尤其重要,因为该服务是从C:\ Windows \ System32启动的,因此您将拥有该工作目录。我将改用GraemeF的方法。
上面提到的方法将当前路径作为URI返回(即“ file:// c:\\ data”)。起作用的是:
System.Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location ) );
它实际上是“ System.IO.Path”。因此具有正确名称空间的标准名称应为:System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly()。Location)
Noelicus:根据答案和评论,几乎总是可以正常工作的安全,准确的方法是:System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly()。Location)