2010-07-17 68 views
5

我知道在执行代码的同一个目录中有一些文件位于其中。我需要找到他们,并通过另一种方法:获取执行代码所在的目录

MyLib.dll 
Target1.dll 
Target2.dll 

Foo(new[] { "..\\..\\Target1.dll", "..\\..\\Target2.dll" }); 

所以我打电话System.IO.Directory.GetFiles(path, "*.dll")。但现在我需要知道的路径:

string path = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName) 

但有更多的短路?

+0

[This post](http://stackoverflow.com/questions/3163495/better-way-to-get-the-base-directory)应该给你几个选项 – mhenrixon 2010-07-17 11:47:36

回答

6

您可以尝试Environment.CurrentDirectory属性。请注意,根据应用程序的类型(控制台,WinForms,ASP.NET,Windows Service,...)及其运行方式,这可能会有所不同。

+0

我正在运行NUnit测试。在现实世界中,我称'Foo(Server.MapPath(“〜/ bin”))'但在测试中,我只是想扫描包含测试的程序集根目录 – abatishchev 2010-07-17 11:48:54

+0

谢谢! 'Environment.CurrentDirectory'就是我一直在寻找的东西。我的电话会从Temp返回一些内容,但您的 - 我正是需要的。 – abatishchev 2010-07-17 12:01:20

+1

Environment.CurrentDirectory在任何时候都不能按预期工作。如果您的应用程序访问标准的Windows文件打开对话框,并且您选择了一些路径,那么下一次调用Environment.CurrentDirectory将返回文件打开对话框中最后选择的路径,而不是执行程序的路径。 – 10100111001 2014-04-30 07:42:52

2

Environment.CurrentDirectory返回当前目录,而不是执行代码所在的目录。如果使用Directory.SetCurrentDirectory,或者如果使用设置目录的快捷方式启动程序,则该目录不会是您正在查找的目录。

坚持原来的解决方案。使用属性隐藏实现(并使其更短):

private DirectoryInfo ExecutingFolder 
{ 
    get 
    { 
     return new DirectoryInfo (
      System.IO.Path.GetDirectoryName (
       System.Reflection.Assembly.GetExecutingAssembly().Location)); 
    } 
}