Better way to get the base directory?

前端 未结 9 1755
旧巷少年郎
旧巷少年郎 2020-12-25 13:59

I have this code to load a config file and read all the values and it works fine when running the application but of course fails on team city because the appdomain\'s base

相关标签:
9条回答
  • 2020-12-25 14:12
    string baseDirectory=Application.StartupPath.Split(Path.DirectorySeparatorChar)[0];
    

    Application startup path will return the path where exe is kept, we will split this using "\" and get the base directory as "C:" for example,

    0 讨论(0)
  • 2020-12-25 14:17

    Your question is a bit unclear. I don't really know if this is what you want.

    I typically use AppDomain.CurrentDomain.BaseDirectory

    Alternatives

    • Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
    • Environment.CurrentDirectory
    0 讨论(0)
  • 2020-12-25 14:17
    string origAssemblyLocation = Assembly.GetExecutingAssembly().CodeBase;
    

    Per MSDN:

    Assembly.CodeBase Property

    Gets the location of the assembly as specified originally

    0 讨论(0)
  • 2020-12-25 14:18

    I like to make my classes configurable - for example they get the folder name as a parameter in their constructor. This makes it possible to test with different config files.

    In test code we use:

    TestContext.TestDeploymentDir
    

    This is the testrun folder, where all assemblies for a test run are copied into, together with the test deployment items. We 'deploy' our unit test config files to the test run folder - this can be specified in the testrunconfig dialog in visual studio.

    For our production code we pass

    Assembly.GetExecutingAssembly().Location
    

    to the constructor, which works for us.

    0 讨论(0)
  • 2020-12-25 14:23

    try this one:

      Module[] modules = Assembly.GetExecutingAssembly().GetModules();
      return Path.GetDirectoryName(modules[0].FullyQualifiedName);
    
    0 讨论(0)
  • 2020-12-25 14:23

    have you tried getting the FileName of the current process' MainModule?

    System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
    

    Or GetEntryAssembly()?

    System.Reflection.Assembly.GetEntryAssembly().Location
    
    0 讨论(0)
提交回复
热议问题