Hi,
Here, an example to get the source folder path of CSharp class via a static method and the package System.Runtime.CompilerServices. In fact, we solicit the compiler in order to get some informations about caller (caller line number, caller method, caller file path): https://msdn.microsoft.com/fr-fr/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx.
02 | using System.Runtime.CompilerServices; |
06 | public class ModelUtility |
08 | public static string getProjectPath([CallerMemberName] string memberName = "" , |
09 | [CallerFilePath] string sourceFilePath = "" , |
10 | [CallerLineNumber] int sourceLineNumber = 0 ) |
13 | string currentClassPath = getInternalPath(); |
14 | string currentProjectPath = Path.GetDirectoryName(currentClassPath); |
15 | return currentProjectPath; |
19 | private static string getInternalPath([CallerMemberName] string memberName = "" , |
20 | [CallerFilePath] string sourceFilePath = "" , |
21 | [CallerLineNumber] int sourceLineNumber = 0 ) |
23 | return sourceFilePath; |
…in the caller method, for example a simple Program.cs, some parameters Callerxxxx are set by compiler:
2 | string currentModelProjectPath = ModelUtility.getProjectPath(); |
06 | public static string getProjectPath([CallerMemberName] string memberName = "" , |
07 | [CallerFilePath] string sourceFilePath = "" , |
08 | [CallerLineNumber] int sourceLineNumber = 0 ) |
06 | private static string getInternalPath([CallerMemberName] string memberName = "" , |
07 | [CallerFilePath] string sourceFilePath = "" , |
08 | [CallerLineNumber] int sourceLineNumber = 0 ) |
That’s all!!!!
Huseyin OZVEREN
Related