JavaBlog.fr / Java.lu C#,DEVELOPMENT CSharp/C# : Get the source folder path of CSharp class

CSharp/C# : Get the source folder path of CSharp class

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.

01using System.IO;
02using System.Runtime.CompilerServices;
03 
04namespace HuoBlog
05{
06    public class ModelUtility
07    {
08        public static string getProjectPath([CallerMemberName] string memberName = "",
09                [CallerFilePath] string sourceFilePath = "",
10                [CallerLineNumber] int sourceLineNumber = 0)
11        {
12            // new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName();
13            string currentClassPath = getInternalPath();
14            string currentProjectPath = Path.GetDirectoryName(currentClassPath);
15            return currentProjectPath;
16        }
17 
18 
19        private static string getInternalPath([CallerMemberName] string memberName = "",
20                [CallerFilePath] string sourceFilePath = "",
21                [CallerLineNumber] int sourceLineNumber = 0)
22        {
23            return sourceFilePath;
24        }
25    }
26}

 
…in the caller method, for example a simple Program.cs, some parameters Callerxxxx are set by compiler:

1//...
2string currentModelProjectPath = ModelUtility.getProjectPath();
3//...
01//...
02// [CallerMemberName] string memberName = "Main"
03// [CallerFilePath] string sourceFilePath = "C:\\Workspaces\\MS_Visual_Studio_Projects\\...\\Program.cs"
04// [CallerLineNumber] int sourceLineNumber = 38
05 
06        public static string getProjectPath([CallerMemberName] string memberName = "",
07                [CallerFilePath] string sourceFilePath = "",
08                [CallerLineNumber] int sourceLineNumber = 0)
09        {
10                //...
11        }
12//...
01//...
02// [CallerMemberName] string memberName = "getProjectPath"
03// [CallerFilePath] string sourceFilePath = "C:\\Workspaces\\MS_Visual_Studio_Projects\\...\\ModelUtility.cs"
04// [CallerLineNumber] int sourceLineNumber = 13
05 
06        private static string getInternalPath([CallerMemberName] string memberName = "",
07                [CallerFilePath] string sourceFilePath = "",
08                [CallerLineNumber] int sourceLineNumber = 0)
09        {
10                //...
11        }
12//...

That’s all!!!!

Huseyin OZVEREN

Tags: , , , ,

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post