I am amazed by the haphazardness of all of the solutions posted so far.
The one and only proper way to get the root folder of a C# project is to leverage the [CallerFilePath]
attribute to obtain the full path name of a source file, and then subtract the filename plus extension from it, leaving you with the path to the project.
Here is how to actually do it:
In the root folder of your project, add file ProjectSourcePath.cs
with the following content:
internal static class ProjectSourcePath
{
private const string myRelativePath = nameof(ProjectSourcePath) + ".cs";
private static string? lazyValue;
public static string Value => lazyValue ??= calculatePath();
private static string calculatePath()
{
string pathName = GetSourceFilePathName();
Assert( pathName.EndsWith( myRelativePath, StringComparison.Ordinal ) );
return pathName.Substring( 0, pathName.Length - myRelativePath.Length );
}
}
The string?
requires a pretty late version of C# with #nullable enable
; if you don't have it, then just remove the ?
.
The Assert()
function is my own, replace it with your own.
The function GetSourceFilePathName()
is defined as follows:
using System.Runtime.CompilerServices
public static string GetSourceFilePathName( [CallerFilePath] string? callerFilePath = null ) //
=> callerFilePath ?? "";
Once you have this, you can use it as follows:
string projectSourcePath = ProjectSourcePath.Value;