我如何获得Bin Path?


79

我需要执行程序集的bin路径。你怎么得到的?我在Bin / Debug中有一个文件夹Plugins,我需要获取位置


你为什么需要这个?为什么应用程序没有路径,似乎找到了合适的程序集?您的部署是什么样的?
麦凯

Answers:


118

这是获取应用程序执行路径的方法:

var path = System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

MSDN有关如何确定执行应用程序的路径的完整参考。

请注意,中的值path将采用的形式file:\c:\path\to\bin\folder,因此在使用路径之前,您可能需要先file:\去除前部。例如:

path = path.Substring(6);

您好,感谢您的及时答复。为什么如果我对路径进行硬编码会找到它,而如果执行以下代码则不会找到它。我可以看到的唯一区别是“ \\”。我想念什么吗?var binpath = Path.GetDirectoryName(Assembly.GetExecutingAssembly()。GetName()。CodeBase); var fullpath = Path.Combine(binpath,folderName); 如果(!Directory.Exists(fullpath))返回;
user9969

6
在我的情况下,问题是System.IO.Path.GetDirectoryName()返回的路径开头是“ file:\\”。我只是将其从字符串中删除,一切正常。
HeitorCorrêa2015年

这似乎进入了out目录
Demodave

1
路径= System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly()。CodeBase); 这对我
有用

6
我建议使用.Replace(“ file:\\”,“”)删除文件前缀,因为它更特定于该问题。
TinyRacoon

69

你可以这样做

    Assembly asm = Assembly.GetExecutingAssembly();
    string path = System.IO.Path.GetDirectoryName(asm.Location);

10
或这个!System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
GoNeale 2014年

9
如果您正在运行NUnit测试,则似乎不起作用。在这种情况下,路径指向TEMP目录。
tponthieux 2014年

您不想要入口组装吗?
N-ate

28

这是我用来完成此任务的:

System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, System.AppDomain.CurrentDomain.RelativeSearchPath ?? "");

2
谢谢,这在IIS托管和Winform中非常有效。
dynamiclynk

谢谢!这似乎适用于ASP.NET应用程序和控制台应用程序。在asp.netRelativeSearchPath中包含实际的“bin”文件夹并在控制台应用程序,这是nullBaseDirectory包含实际的“bin”的路径。
Mariusz Pawelski


8
Path.GetDirectoryName(Application.ExecutablePath)

例如。值:

C:\Projects\ConsoleApplication1\bin\Debug

8
注意:此解决方案仅适用于Windows.Forms
m1m1k 2015年

3
var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)?.Replace("file:\\", "");
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.