简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM