Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the path to the current C# source code file?

Tags:

c#

.net

file

path

io

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.)

like image 624
James Ko Avatar asked Dec 16 '17 00:12

James Ko


1 Answers

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");
like image 199
James Ko Avatar answered Oct 03 '22 20:10

James Ko