Skip to content

Instantly share code, notes, and snippets.

@chrcar01
Last active March 19, 2022 20:56
Show Gist options
  • Save chrcar01/66cae6b3d6abe34ac23b9b9ec1fde5bc to your computer and use it in GitHub Desktop.
Save chrcar01/66cae6b3d6abe34ac23b9b9ec1fde5bc to your computer and use it in GitHub Desktop.
Code to find project root path in a visual studio project
using System.Runtime.CompilerServices;
// Ripped from S.O. answer: https://stackoverflow.com/a/66285728/1594171
// 1. Put this code in ProjectSourcePath.cs at root of project
// 2. Reference project path like this: ProjectSourcePath.Value
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();
return pathName.Substring(0, pathName.Length - myRelativePath.Length);
}
public static string GetSourceFilePathName([CallerFilePath] string? callerFilePath = null) =>
callerFilePath ?? "";
}
@chrcar01
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment