C# 获取引用的本地程序集的位置
在我的解决方案中,ProjectB引用了ProjectA。在运行ProjectB时,我试图获得ProjectA的“路径” 我试过这个: 在项目B中运行C# 获取引用的本地程序集的位置,c#,asp.net,.net,C#,Asp.net,.net,在我的解决方案中,ProjectB引用了ProjectA。在运行ProjectB时,我试图获得ProjectA的“路径” 我试过这个: 在项目B中运行 // HomeController is in ProjectA // This code is executed from ProjectB var assembly = typeof(HomeController ).Assembly; string filePath = new Uri(assembly.CodeBase).LocalPat
// HomeController is in ProjectA
// This code is executed from ProjectB
var assembly = typeof(HomeController ).Assembly;
string filePath = new Uri(assembly.CodeBase).LocalPath;
返回ProjectB路径,而不是ProjectA路径
编辑:
这将在路径中显示UnitTestProject1。我想获取WebApplication1的路径
要获取引用程序集的位置,请使用此
System.Reflection.Assembly.GetAssembly(typeof(SmsController)).Location;
我认为您必须确保要引用的文件被复制到项目B(主项目)的bin文件夹中。然后您可以使用以下代码:
string code = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(code);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
这将返回到bin文件夹的路径
我认为您必须将要引用的文件添加为被占用的资源或链接的资源:那么,您确定来自ProjectA的
SmsController
?它可以工作,您只需要从assemblyYes传递类型。SmSController在ProjectA中。我有2个项目的简单解决方案。就这样。一个是Web,另一个是UnitTests。单元测试参考Web@ShaneKm这是正常的,因为您引用的dll复制到正在运行的项目的bin中。所以,它显示了使用的程序集的路径(从bin文件夹)。如果您只想找到Web项目的路径,那么您可以在.csproj文件中查看并找到ProjectReference Include=“..\..\..\ProjectA.csproj”
并使用类似的方法