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.

using System.IO;
using System.Runtime.CompilerServices;

namespace HuoBlog
{
    public class ModelUtility
    {
        public static string getProjectPath([CallerMemberName] string memberName = "",
                [CallerFilePath] string sourceFilePath = "",
                [CallerLineNumber] int sourceLineNumber = 0)
        {
            // new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName();
            string currentClassPath = getInternalPath();
            string currentProjectPath = Path.GetDirectoryName(currentClassPath);
            return currentProjectPath;
        }


        private static string getInternalPath([CallerMemberName] string memberName = "",
                [CallerFilePath] string sourceFilePath = "",
                [CallerLineNumber] int sourceLineNumber = 0)
        {
            return sourceFilePath;
        }
    }
}

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

//...
string currentModelProjectPath = ModelUtility.getProjectPath();
//...
//...
// [CallerMemberName] string memberName = "Main"
// [CallerFilePath] string sourceFilePath = "C:\\Workspaces\\MS_Visual_Studio_Projects\\...\\Program.cs"
// [CallerLineNumber] int sourceLineNumber = 38

        public static string getProjectPath([CallerMemberName] string memberName = "",
                [CallerFilePath] string sourceFilePath = "",
                [CallerLineNumber] int sourceLineNumber = 0)
        {
                //...
        }
//...
//...
// [CallerMemberName] string memberName = "getProjectPath"
// [CallerFilePath] string sourceFilePath = "C:\\Workspaces\\MS_Visual_Studio_Projects\\...\\ModelUtility.cs"
// [CallerLineNumber] int sourceLineNumber = 13

        private static string getInternalPath([CallerMemberName] string memberName = "",
                [CallerFilePath] string sourceFilePath = "",
                [CallerLineNumber] int sourceLineNumber = 0)
        {
                //...
        }
//...

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