C# 获取引用程序集中的相对路径 [英] C# Get relative path in referenced assembly
问题描述
我有 2 个项目 Project A , Project B ,项目 A 引用了项目 B ,项目 A 是一个可执行文件.
I have 2 projects Project A , Project B , project A has a reference to project B , project A is an executable.
Project A --> Project B
在项目 B 中有一个名为MyFolder"的目录
inside project B there is a directory called "MyFolder"
所以灵魂层次如下:
MySolution
- A
- B
- MyFolder
如何从项目 A(可执行文件)中获取 MyFolder 的相对路径.
how do i get a Relative Path to MyFolder from with in project A(Executable).
我找到了很多答案,说明如下:
I found allot of answer which state the following :
sring path = Assembly.GetAssembly(typeof(SomeClassInBProject)).Location;
我从这里返回的路径是 A 的 bin\debug 中 B.dll 的路径,我如何检索该 .dll 中的路径.
The path i got back from this is the path to B.dll in A's bin\debug ,how can i retrieve a path with in that .dll .
我也试过:
Assembly assembly = Assembly.GetAssembly(typeof(SomeClassInBProject));
FileStream fs = assembly.GetFile(@"MyFolder\myFile");
and
FileStream fs = assembly.GetFile("MyFolder\myFile");
and
FileStream fs = assembly.GetFile("myFile");
fs i 始终为空.
推荐答案
Is Uri.MakeRelativeUri 你在找什么?
string pathA = Assembly.GetExecutingAssembly().Location;
string pathB = Assembly.GetAssembly(typeof(SomeClassInBProject)).Location;
Uri pathAUri = new Uri(pathA);
Uri pathBUri = new Uri(pathB);
string relativePath = pathAUri.MakeRelativeUri(pathBUri).OriginalString;
string relativeMyFolder = Path.Combine(relativePath, "MyFolder");
更新
您可以使用 Assembly.GetFile() 方法返回一个 FileStream.FileStream
有一个 Name
属性,你可以在上面的代码中使用.
You can use the Assembly.GetFile() method which returns a FileStream. FileStream
has a Name
property you could use in the code above.
这篇关于C# 获取引用程序集中的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!