C# Get relative path in referenced assembly

北慕城南 提交于 2019-12-22 05:25:10

问题


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 

inside project B there is a directory called "MyFolder"

so the soulotion hierarchy is as follows :

    MySolution 
       -  A
       -  B 
          - 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;

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 .

Edit :

iv'e also tried :

        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 always null.


回答1:


Is Uri.MakeRelativeUri what you're looking for?

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

Update

You can use the Assembly.GetFile() method which returns a FileStream. FileStream has a Name property you could use in the code above.




回答2:


Unless there is some reason that you can't do this, I recommend opening the Properties Window* and setting the Build Action property to Embedded Resource and making sure that Copy to Output Directory is set to Do not copy. You can then use Assembly.GetFile() to access it.

Assembly assembly = Assembly.GetAssembly(typeof(SomeClassInBProject));
using (FileStream fs = assembly.GetFile("myfile"))
{
    // Manipulate the FileStream here
}

*With the file selected, press Alt + Enter or right-click on the file and select Properties



来源:https://stackoverflow.com/questions/21955109/c-sharp-get-relative-path-in-referenced-assembly

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