Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine current path with DNX projects

Target

For integration tests I want to load a custom XML configuration. This XML is located in a folder inside my integration test project.

For further targets I want to use the new DNX projects. I know they are still in preview.

Local tests work fine. The problem is now, that I cannot use relative paths, because of the test system the current directory information is not the project folder of my project. The same issue with AppVeyor.

The build agent is started in another folder and so the relative path information is wrong and fails. No suprise here.

I've tried to solve this with this snippet:

public abstract class IntegrationTestBase
{
    public static string CurrentPath()
    {
        string codeBase = typeof (IntegrationTestBase).Assembly.Location;
        UriBuilder uri = new UriBuilder( codeBase );
        string path = Uri.UnescapeDataString( uri.Path );
        return Path.GetDirectoryName( path );
    }
}

Problem

The problem here is: because of the new DNX Runtime this returns not the location of my project and/or assembly, it returns the runtime folder:

C:/Users/ben/.dnx/runtimes/dnx-clr-win-x86.1.0.0-rc1-update1/bin/Microsoft.Dnx.Loader.dll

Same behavior if I ask for CodeBase or Executing/CallingAssembly.

With "old" simple C# projects and MsTest, I get the path as expected.

Environment.CurrentDirectory does not work on AppVeyor, because process is not started in project folder and then this command returns another path (the path of the started project).

Question

What is the correct way to work with relative paths here?

Environment

  • VS 2015 Update 1
  • DNX Project templates
  • xUnit configuration
  • AppVeyor build system
like image 234
Benjamin Abt Avatar asked Jan 19 '16 14:01

Benjamin Abt


1 Answers

In DNX projects you have to add the dependency Microsoft.Extensions.PlatformAbstractions and can then use PlatformServices.Default.Application.ApplicationBasePath

Or even easier without additional dependency: use System.AppContext.BaseDirectory

Maybe because of future native compiling the reflection stuff would not work. I think System.AppContext.BaseDirectory is the easiest solution. PlatformServices.Default.Application inherits the IApplicationEnvironment interface which is injected by default in new ASP.NET Core applications.

like image 126
Benjamin Abt Avatar answered Nov 04 '22 15:11

Benjamin Abt