代码之家  ›  专栏  ›  技术社区  ›  abatishchev Karl Johan

获取执行代码所在的目录

  •  5
  • abatishchev Karl Johan  · 技术社区  · 14 年前

    我知道在执行代码的同一个目录中,有一些文件位于同一个目录中。我需要找到它们并传递到另一种方法:

    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)
    

    但是还有近路吗?

    2 回复  |  直到 9 年前
        1
  •  6
  •   Darin Dimitrov    14 年前

    你可以试试 Environment.CurrentDirectory 财产。请注意,根据应用程序的类型(控制台、WinForms、ASP.NET、Windows服务等)及其运行方式,这可能表现出不同的行为。

        2
  •  2
  •   Harald Coppoolse    9 年前

    environment.current directory返回当前目录,而不是执行代码所在的目录。如果您使用directory.setcurrentdirectory,或者使用设置目录的快捷方式启动程序,则这将不是您要查找的目录。

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

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