How to get Current Project Directory path using C#

后端 未结 9 776
旧巷少年郎
旧巷少年郎 2020-12-31 08:19

okay, here is the question. I have two projects one is C# Console and other is Class library. I am accessing/calling Class library method from the console app. There is a fo

相关标签:
9条回答
  • 2020-12-31 08:46

    I had this exact issue as well where I couldn't access the file in my namespace's bin/debug folder. My solution was to manipulate the string using Split() then construct a new string which is the absolute path to the json file I have in my namespace.

    private static string GetFilePath()
            {            
                const char Escape = '\\'; //can't have '\' by itself, it'll throw the "Newline in constant" error
                string directory = Environment.CurrentDirectory;
                string[] pathOccurences = directory.Split(Escape);            
                string pathToReturn = pathOccurences[0] + Escape; //prevents index out of bounds in upcoming loop
                for(int i = 1; i < pathOccurences.Length; i++)
                {
                    if (pathOccurences[i] != pathOccurences[i - 1]) //the project file name and the namespace file name are the same
                        pathToReturn += pathOccurences[i] + Escape;
                    else
                        pathToReturn += typeof(thisClass).Namespace + Escape; //In the one occurrence of the duplicate substring, I replace it with my class Namespace name
                }
                return pathToReturn + "yourFile.json";
            }
    

    I personally don't like this solution, but it was the only answer I could think of.

    0 讨论(0)
  • 2020-12-31 08:53

    I use the following approach to get the current project path at runtime:

    public static class ProjectInfo {
       public static string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
       public static string projectPath = appDirectory.Substring(0, appDirectory.IndexOf("\\bin"));
    }
    
    0 讨论(0)
  • 2020-12-31 08:54

    I believe the problem is:

    Since the Console project has the DLL file reference it is using DLL to call any methods. At this time it is returning the class library projct's DLL location which is located in console project's bin directory and it doesn't know about the physical location of class library project.

    so essentially it is returning the same project path. I will have to move both projects in same directory in order to solve this issue.

    0 讨论(0)
提交回复
热议问题