繁体   English   中英

获取执行代码所在的目录

[英]Get directory where executed code is located

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

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)

但还有更短的路吗?

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM