Search code examples
c#appdomainvstest.console.exeappdomainsetup

AppDomain.DynamicDirectory is not generated


I am creating a AppDomain using the below code

String pa = @"C:\Users\user\AppData\Local\Temp\2\db5fjamk.xnl";
System.IO.Directory.CreateDirectory(pa);
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; //f:\projectpath\out\debug-i386-unittest\UnitTests
setup.ApplicationName = string.Concat(AppDomain.CurrentDomain.FriendlyName, DateTime.UtcNow.Ticks); //UnitTestAdapter: Running test636559691791186101
setup.DynamicBase = pa;
Evidence evidence = AppDomain.CurrentDomain.Evidence;
_Domain = AppDomain.CreateDomain(setup.ApplicationName, evidence, setup);

But _Domain.DynamicDirectory property does not exist. https://msdn.microsoft.com/en-us/library/system.appdomain.dynamicdirectory(v=vs.110).aspx clearly says the AppDomainSetup.DynamicBase is used.

What could be the reason executing in vstest.console.exe changes the behavior with App Domains. Is there a work around.


Solution

  • Solution

    Check if the AppDomain.CurrentDomain.FriendlyName contains illegal characters such as a colon (:). If yes you should sanitize setup.ApplicationName with one of the methods discussed in the SO question How to remove illegal characters from path and filenames?.

    Background

    When I debugged the test I got a System.NotSupportedException with the message The given path's format is not supported..

    The stack trace was

    at System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String fullPath)
    at System.Security.Permissions.FileIOPermission.QuickDemand(FileIOPermissionAccess access, String fullPath, Boolean checkForDuplicates, Boolean needFullPath)
    at System.AppDomain.get_DynamicDirectory()
    at System.AppDomain.get_DynamicDirectory()
    at SO_AppDomain.Sut.Method() in <path>\Program.cs:line 30
    at UnitTestProject1.UnitTest1.TestMethod1() in <path>\UnitTest1.cs:line 14
    

    And the value of AppDomain.CurrentDomain.FriendlyName was TestSourceHost: Enumering assembly.

    A quick look at the reference source of EmulateFileIOPermissionChecks - which is the last method that appears in the stack trace - revealed that it throws a NotSupportedException if PathInternal.HasInvalidVolumeSeparator returns true. That method contains the following comment:

     // Toss out paths with colons that aren't a valid drive specifier.
     // Cannot start with a colon and can only be of the form "C:" or "\\?\C:".
    

    The string TestSourceHost: Enumering assembly clearly violates that rule.