Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Get relative path in referenced assembly

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.

like image 243
eran otzap Avatar asked Feb 22 '14 13:02

eran otzap


1 Answers

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.

like image 131
keyboardP Avatar answered Oct 17 '22 18:10

keyboardP