How do I get the path to the current C# source code file, or the directory the file is stored in? (I'm answering this question myself because I didn't find anything on it with a Google search.)
(Note: This is not asking for Assembly.GetEntryAssembly().Location
, which gives the path to the executable, nor Directory.GetCurrentDirectory()
, which gives the directory the process was invoked from.)
Do this:
using System.Runtime.CompilerServices;
private static string GetThisFilePath([CallerFilePath] string path = null)
{
return path;
}
var path = GetThisFilePath(); // path = @"path\to\your\source\code\file.cs"
var directory = Path.GetDirectoryName(path); // directory = @"path\to\your\source\code"
How it works: Roslyn specially recognizes the CallerFilePath
, CallerLineNumber
, and CallerMemberName
attributes (the last one might look familiar to you if you've done some MVVM programming). At compile-time, it populates parameters marked with these attributes with the actual file path / line number / member name of the caller. If you compile and decompile the above code, the assignment to path
will look like
var path = GetThisFilePath(@"path\to\your\source\code\file.cs");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With