How to get Current Project Directory path using C#

后端 未结 9 775
旧巷少年郎
旧巷少年郎 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:39

    If you loading the class library from another assembly.

    string Path = System.Reflection.Assembly.GetAssembly(typeof({LibraryClassName})).Location;
    
    string PathToClassLibPro = Path.GetDirectoryName( Path);
    

    Replace {LibraryClassName} with the class name of your library.

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

    I would recommend one of two options.

    1. If the files are small include them in the class library and stream them to a temp location when needed

    2. Other option is to copy the files during the build to the output directory and use them that way. In cases of multiple shared projects it is best to have a common bin folder that you copy assemblies to and run from that location.

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

    Once the code is compiled and running, 'Project Path' has no meaning. All you can determine are the file locations of the compiled assemblies. And you can only do what you are asking if your Console project references the built 'class library' DLL directly, rather than via a Project Reference.

    Then, you can make use of Reflection to get Assembly paths like;

    string path = Assembly.GetAssembly(typeof (SomeClassInOtherProject)).Location;
    
    0 讨论(0)
  • 2020-12-31 08:44

    I hope I understand u corretly:

    Path.GetDirectoryName(typeof(Foo.MyFooClass).Assembly.Location);
    
    0 讨论(0)
  • 2020-12-31 08:45

    Despite i cant find a good solution i use this trick : as long as you want to come back to your ideal path u should add Directory.GetParent() instead of ...

      Directory.GetParent(...(Directory.GetParent(Directory.GetCurrentDirectory()).ToString()...).ToString()
    
    0 讨论(0)
  • 2020-12-31 08:46

    You should be able to use Directory.GetParent(Directory.GetCurrentDirectory()) a few times to get higher level directories and then add the path of the lib directory to the end of that.

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