问题
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