Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve Current Directory when running Coded UI

I am running a CodedUI test that references a DLL and that DLL refrences a sort of "config" file. While running the test the current Directory returns the one where CodedUI puts the test results files I've used

AppDomain.CurrentDomain.BaseDirectory

and

System.Reflection.Assembly.GetExecutingAssembly().CodeBase

and

System.Reflection.Assembly.GetExecutingAssembly().Location

These all give me the same path

What I need is to get the path where the DLL resides because that is where the config file will be built.

The location where this will be changes if I am debugging or if I am just running the test (obviously) so I can't use that and navigate backwards or anything like that.

Are there any other ways to get the location of the DLL you are referencing??

Edit:

I am referencing this config file from inside the DLL that i am referencing.

like image 563
Jordan Davidson Avatar asked Oct 07 '22 06:10

Jordan Davidson


2 Answers

So far the only place I have found the original path to the test dll is in a private variable in the test context. I ended up using reflection to get the value out and make it usable.

    using System.Reflection;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    public static string CodeBase(
        TestContext testContext)
    {
        System.Type t = testContext.GetType();
        FieldInfo field = t.GetField("m_test", BindingFlags.NonPublic | BindingFlags.Instance);
        object fieldValue = field.GetValue(testContext);
        t = fieldValue.GetType();
        PropertyInfo property = fieldValue.GetType().GetProperty("CodeBase");
        return (string)property.GetValue(fieldValue, null);
    }

I used this to get the path to the DLL that is getting run and use that to then run the application that I know is compiled to the same location as the test was at.

If anyone finds a better way of getting this, please let me know as well.

like image 112
David Parvin Avatar answered Oct 10 '22 04:10

David Parvin


The best way to get the directory of where a given DLL was loaded from is to use the following on a type that is defined in that assembly.

var type = typeof(TypeInThatAssembly);
var path = Path.GetDirectory(type.Location);

The CodeBase and Location property often return the same information but are very different

  • CodeBase: This contains the location for the assembly as it was referenced during load
  • Location: This is where the assembly was actually loaded from on disk

These can differ in application which use shadow copied assemblies (Asp.Net, xUnit, etc ...)

like image 40
JaredPar Avatar answered Oct 10 '22 02:10

JaredPar