Get directory where executed code is located

对着背影说爱祢 提交于 2019-12-10 14:18:11

问题


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"). But now I need to get know the path:

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

but is there more short way?


回答1:


You may try the Environment.CurrentDirectory property. Note that depending on the type of application (Console, WinForms, ASP.NET, Windows Service, ...) and the way it is run this might behave differently.




回答2:


Environment.CurrentDirectory returns the current directory, not the directory where the executed code is located. 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.

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));
    }
}


来源:https://stackoverflow.com/questions/3271326/get-directory-where-executed-code-is-located

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!