简体   繁体   English

获取执行代码所在的目录

[英]Get directory where executed code is located

I know that in the same directory where my code is being executed some files are located. 我知道在我的代码执行的同一目录中有一些文件。 I need to find them and pass to another method: 我需要找到它们并传递给另一种方法:

MyLib.dll
Target1.dll
Target2.dll

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

So I call System.IO.Directory.GetFiles(path, "*.dll") . 所以我调用System.IO.Directory.GetFiles(path, "*.dll") But now I need to get know the path: 但现在我需要了解路径:

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

but is there more short way? 但还有更短的路吗?

You may try the Environment.CurrentDirectory property. 您可以尝试使用Environment.CurrentDirectory属性。 Note that depending on the type of application (Console, WinForms, ASP.NET, Windows Service, ...) and the way it is run this might behave differently. 请注意,根据应用程序的类型(控制台,WinForms,ASP.NET,Windows服务,...)及其运行方式,这可能会有所不同。

Environment.CurrentDirectory returns the current directory, not the directory where the executed code is located. Environment.CurrentDirectory返回当前目录,而不是执行代码所在的目录。 If you use Directory.SetCurrentDirectory, or if you start the program using a shortcut where the directory is set this won't be the directory you are looking for. 如果使用Directory.SetCurrentDirectory,或者如果使用设置目录的快捷方式启动程序,则这将不是您要查找的目录。

Stick to your original solution. 坚持原始解决方案。 Hide the implementation (and make it shorter) using a property: 使用属性隐藏实现(并使其更短):

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