简体   繁体   中英

Get the path of the current file

All the solutions I've found for getting the path of the current file do not work in two situations: when running unit tests from another project in the solution, and when accessing the project from another project with a reference.

When running unit tests, the path generated by these are all relative to the Test project in my solution, and this causes the path I'm building to access some assets to be incorrect:

System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
System.AppDomain.CurrentDomain.BaseDirectory;
System.Environment.CurrentDirectory;
System.IO.Directory.GetCurrentDirectory();
Environment.CurrentDirectory;
Thread.GetDomain().BaseDirectory;
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
System.IO.Path.GetFullPath(@"..\..\");

They all output the wrong project when running unit tests: C:\\Users\\Me\\source\\MySolution\\TestProject\\bin\\Debug

I need it to output the same path to the correct project:
C:\\Users\\Me\\source\\MySolution\\CoolProject\\classes\\somefile.cs or C:\\Users\\Me\\source\\MySolution\\CoolProject\\classes or C:\\Users\\Me\\source\\MySolution\\CoolProject\\ or C:\\Users\\Me\\source\\MySolution\\CoolProject\\bin\\debug

How to generate a path to the current file or at least the project that the code resides within?

The *.cs is lost during compilation. You can preserve it by having a method with some default parameters and [CallerMemberName] for the method, [CallerFilePath] for the file name and [CallerLineNumber] for the line from which your method is called, then return one of the values received.

public string GetMyFilePath([CallerFilePath] string callerFilePath = null) => return callerFilePath;

invoke it with no parameters and it will return the path to the file you're calling from.... for as long as that's on the same machine where the code was built

You can also get the dll path from Assembly.GetExecutingAssembly().CodeBase . This gives you the full path to the dll with file:/// in front, but not the source file name.

It would be good to elaborate on your objective, there may be a different and better way to do what you're trying to do.

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