JOberloh
JOberloh

Reputation: 1106

How can I return C# class file path

I am attempting to retrieve an individual file path for any given class. For example, I have the class AuthorizeOverrideBalancingPopup.cs in the following filepath:

C:\development\pom\PageObjectModel\PageObjects\Panel\AuthorizeOverrideBalancingPopup.cs

Are there any C# methods that I can use in order to return that full file path? It seems like most other similar questions return the directory of the IDE instead of the class itself, which is in a completely different directory.

Upvotes: 3

Views: 2665

Answers (2)

ispiro
ispiro

Reputation: 27693

Your program will run somewhere where those files do not exist. They are compiled into an exe file and are not "shipped" with the code.

The other answer here refers to the code at compile time (See MSDN) and won't be there when the file is executed on the target machine. (Though perhaps that's what you're looking for?)

EDIT according to your comment ("to then be able to scrape the class name")

use this.GetType().Name or typeof(Class1).Name or nameof(Class1) [from C# 6]

Upvotes: 2

logix
logix

Reputation: 642

You could use the CallerFilePath attribute:

static void Main(string[] args)
{
    Console.WriteLine(GetPath());
    Console.Read();
}

static string GetPath([CallerFilePath]string fileName = null)
{
    return fileName;
}

Upvotes: 6

Related Questions