Determine C# code class file's parent directory path at design-time

80 views Asked by At

Here is info about our technical development environment :

• .NET Core 3.1

• PostgreSQL 14.2, compiled by Visual C++ build 1914, 64-bit

• EntityFramework.Functions Version=1.5.0

• Microsoft.EntityFrameworkCore.Design Version=5.0.17

• Microsoft.EntityFrameworkCore.Tools Version=5.0.17

• Npgsql.EntityFrameworkCore.PostgreSQL Version=5.0.10

The location of a C# code file called JohnDoeCSharp.cs is located in VisualStudioProjectDir\Migrations\1.0.5

It contains the following code constructor:

public class JohnDoeCSharp
{
    public JohnDoeCSharp()
    {
        
    }
}

Within the aforementioned constructor, I’m trying to get the name of the parent directory called 1.0.5

The problem with using the following code is that they give runtime directory paths values back:

string strExeFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

string strWorkPath = System.IO.Path.GetDirectoryName(strExeFilePath);

For lack of a better term, I suppose I’m trying to get the directory path values at design time / “coding time”.

What can I try next?

1

There are 1 answers

0
NineBerry On

You can write a helper method that uses the CallerFilePath attribute to get the directory of a code file.

Helper class:

public static class CodeHelper
{
    public static string GetCodeDirectory([CallerFilePath]string filepath = "")
    {
        return Path.GetDirectoryName(filepath);
    }
}

Usage:

internal class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(CodeHelper.GetCodeDirectory());
    }
}