Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取执行代码所在的目录_C#_.net_Getfiles - Fatal编程技术网

C# 获取执行代码所在的目录

C# 获取执行代码所在的目录,c#,.net,getfiles,C#,.net,Getfiles,我知道在执行代码的同一个目录中有一些文件。我需要找到它们并传递给另一种方法: MyLib.dll Target1.dll Target2.dll Foo(new[] { "..\\..\\Target1.dll", "..\\..\\Target2.dll" }); 所以我调用System.IO.Directory.GetFiles(路径“*.dll”)。但现在我需要知道路径: string path = new FileInfo((Assembly.GetExecutingAssembly

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

MyLib.dll
Target1.dll
Target2.dll

Foo(new[] { "..\\..\\Target1.dll", "..\\..\\Target2.dll" });
所以我调用
System.IO.Directory.GetFiles(路径“*.dll”)
。但现在我需要知道路径:

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

但是还有别的捷径吗?

你可以试试这家酒店。请注意,根据应用程序的类型(控制台、WinForms、ASP.NET、Windows服务等)及其运行方式,其行为可能有所不同。

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

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

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

我在做NUnit测试。在现实世界中,我调用
Foo(Server.MapPath(“~/bin”)
,但在测试中,我只想扫描包含测试的程序集的根目录谢谢<代码>环境。CurrentDirectory是我要找的。我的呼叫从Temp返回了一些内容,但您的-正是我需要的。Environment.CurrentDirectory并非始终按预期工作。如果您的应用程序访问标准Windows文件打开对话框,并且您在其中选择了一些路径,那么下一次调用Environment.CurrentDirectory将返回文件打开对话框中最后选择的路径,而不是执行程序的路径。应该给你一些选择