AppDomain.DynamicDirectory 屬性

定義

取得組件解析程式用來探查動態建立之組件的目錄。Gets the directory that the assembly resolver uses to probe for dynamically created assemblies.

public:
 property System::String ^ DynamicDirectory { System::String ^ get(); };
public string? DynamicDirectory { get; }
public string DynamicDirectory { get; }
member this.DynamicDirectory : string
Public ReadOnly Property DynamicDirectory As String

屬性值

String

組件解析程式用來探查以動態建立組件的目錄。The directory that the assembly resolver uses to probe for dynamically created assemblies.

實作

例外狀況

嘗試對卸載的應用程式定義域執行作業。The operation is attempted on an unloaded application domain.

範例

下列範例會建立具有動態元件目錄的應用程式域、發出動態元件,並將它儲存在動態目錄中,然後將元件載入至新的應用程式域,並加以使用。The following example creates an application domain with a directory for dynamic assemblies, emits a dynamic assembly and stores it in the dynamic directory, and then loads the assembly into the new application domain and uses it.

此範例會建立 AppDomainSetup 物件,並將其 ApplicationName 屬性設定為 "example",並將其 DynamicBase 屬性設定為 "C:\DynamicAssemblyDir"。The example creates an AppDomainSetup object and sets its ApplicationName property to "Example" and its DynamicBase property to "C:\DynamicAssemblyDir". 然後,此範例會顯示 DynamicBase 屬性,以顯示應用程式名稱的雜湊碼已附加為原本指派之路徑的子目錄。The example then displays the DynamicBase property, to show that the hash code of the application name has been appended as a subdirectory of the path that was originally assigned.

注意

此範例中的基底目錄是要在範例應用程式的探查路徑之外。The base directory in this example is intended to be outside the probing path for the example application. 請務必在不同的位置中編譯範例。Be sure to compile the example in a different location. 每次執行此範例時,請刪除基底目錄及其所有子目錄。Delete the base directory and all its subdirectories each time you run the example.

此範例會使用物件來建立新的應用程式域 AppDomainSetupThe example creates a new application domain, using the AppDomainSetup object. 此範例會使用 DynamicDirectory 屬性來抓取目錄的名稱,讓它可以建立目錄。The example uses the DynamicDirectory property to retrieve the name of the directory, so it can create the directory. (範例可以藉由串連原始路徑、應用程式名稱的雜湊程式碼和應用程式名稱,直接建立目錄。 ) (The example could just as easily create the directory beforehand by concatenating the original path, the hash code of the application name, and the application name.)

此範例的 GenerateDynamicAssembly 方法會發出名為的元件 DynamicHelloWorld.dll ,並將其儲存在新的應用程式域的動態目錄中。The example has a GenerateDynamicAssembly method that emits an assembly named DynamicHelloWorld.dll and stores it in the new application domain's dynamic directory. 動態元件包含一種類型, HelloWorldShared 在名為的 Visual Basic) 中具有靜態方法 (方法 HelloFromADThe dynamic assembly contains one type, HelloWorld, that has a static method (Shared method in Visual Basic) named HelloFromAD. 呼叫這個方法會顯示應用程式域的名稱。Calling this method displays the name of the application domain.

Example類別衍生自 MarshalByRefObject ,因此範例可以在新的應用程式域中建立類別的實例,並呼叫其 Test 方法。The Example class derives from MarshalByRefObject, so the example can create an instance of the class in the new application domain and call its Test method. Test方法會依其顯示名稱載入動態元件,並呼叫靜態 HelloFromAD 方法。The Test method loads the dynamic assembly by its display name and calls the static HelloFromAD method.

您可以藉由撰寫名為之元件的程式碼 DynamicHelloWorld.dll ,並在與此範例相同的目錄中進行編譯,顯示在一般探查路徑之後搜尋動態目錄。You can show that the dynamic directory is searched after the normal probing paths by writing code for an assembly named DynamicHelloWorld.dll and compiling it in the same directory as this example. 元件必須有一個名為 HelloWorld 的類別,且該類別具有名為的靜態方法 HelloFromADThe assembly must have a class named HelloWorld with a static method named HelloFromAD. 這個方法不需要與範例中的功能相同:它可以直接在主控台中顯示字串。This method does not have to have the same functionality as the one in the example; it can simply display a string to the console. 元件也必須有 AssemblyVersionAttribute 屬性,將其版本設定為1.0.0.0。The assembly must also have an AssemblyVersionAttribute attribute that sets its version to 1.0.0.0. 當您執行範例時,會在搜尋動態目錄之前,找到您在目前的目錄中編譯的元件。When you run the example, the assembly you compiled in the current directory is found before the dynamic directory is searched.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;

public ref class Example : MarshalByRefObject
{
public:
   void Test()
   {
      Assembly^ dynAssem = Assembly::Load(
         "DynamicHelloWorld, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");

      Type^ myType = dynAssem->GetType("HelloWorld");
      myType->InvokeMember("HelloFromAD", BindingFlags::Public | 
         BindingFlags::Static | BindingFlags::InvokeMethod, 
         Type::DefaultBinder, nullptr, nullptr);
   }
};


static void GenerateDynamicAssembly(String^ location)
{
   // Define the dynamic assembly and the module. There is only one
   // module in this assembly. Note that the call to DefineDynamicAssembly 
   // specifies the location where the assembly will be saved. The 
   // assembly version is 1.0.0.0.
   //
   AssemblyName^ asmName = gcnew AssemblyName("DynamicHelloWorld");
   asmName->Version = gcnew Version("1.0.0.0");

   AssemblyBuilder^ ab = 
      AppDomain::CurrentDomain->DefineDynamicAssembly( 
         asmName, AssemblyBuilderAccess::Save, location);

   String^ moduleName = asmName->Name + ".exe";
   ModuleBuilder^ mb = ab->DefineDynamicModule(asmName->Name, moduleName);
   
   // Define the "HelloWorld" type, with one static method.
   TypeBuilder^ tb = mb->DefineType("HelloWorld", TypeAttributes::Public);
   MethodBuilder^ hello = tb->DefineMethod("HelloFromAD", 
      MethodAttributes::Public | MethodAttributes::Static, nullptr, nullptr);

   // The method displays a message that contains the name of the application
   // domain where the method is executed.
   ILGenerator^ il = hello->GetILGenerator();
   il->Emit(OpCodes::Ldstr, "Hello from '{0}'!");
   il->Emit(OpCodes::Call, AppDomain::typeid->GetProperty("CurrentDomain")->GetGetMethod());
   il->Emit(OpCodes::Call, AppDomain::typeid->GetProperty("FriendlyName")->GetGetMethod());
   il->Emit(OpCodes::Call, Console::typeid->GetMethod("WriteLine", 
                            gcnew array<Type^> { String::typeid, String::typeid }));
   il->Emit(OpCodes::Ret);

   // Complete the HelloWorld type and save the assembly. The assembly
   // is placed in the location specified by DefineDynamicAssembly.
   Type^ myType = tb->CreateType();
   ab->Save(moduleName);
};

void main()
{
   // Prepare to create a new application domain.
   AppDomainSetup^ setup = gcnew AppDomainSetup();

   // Set the application name before setting the dynamic base.
   setup->ApplicationName = "Example";
   
   // Set the location of the base directory where assembly resolution 
   // probes for dynamic assemblies. Note that the hash code of the 
   // application name is concatenated to the base directory name you 
   // supply. 
   setup->DynamicBase = "C:\\DynamicAssemblyDir";
   Console::WriteLine("DynamicBase is set to '{0}'.", setup->DynamicBase);

   AppDomain^ ad = AppDomain::CreateDomain("MyDomain", nullptr, setup);
   
   // The dynamic directory name is the dynamic base concatenated with
   // the application name: <DynamicBase>\<hash code>\<ApplicationName>
   String^ dynamicDir = ad->DynamicDirectory;
   Console::WriteLine("Dynamic directory is '{0}'.", dynamicDir);

   // The AssemblyBuilder won't create this directory automatically.
   if (!System::IO::Directory::Exists(dynamicDir))
   {
      Console::WriteLine("Creating the dynamic directory.");
      System::IO::Directory::CreateDirectory(dynamicDir);
   }

   // Generate a dynamic assembly and store it in the dynamic 
   // directory.
   GenerateDynamicAssembly(dynamicDir);

   // Create an instance of the Example class in the application domain,
   // and call its Test method to load the dynamic assembly and use it.
   Example^ ex = (Example^) ad->CreateInstanceAndUnwrap( 
         Example::typeid->Assembly->FullName, "Example");
   ex->Test();
}

/* This example produces output similar to the following:

DynamicBase is set to 'C:\DynamicAssemblyDir\5e4a7545'.
Dynamic directory is 'C:\DynamicAssemblyDir\5e4a7545\Example'.
Creating the dynamic directory.
Hello from 'MyDomain'!
 */
using System;
using System.Reflection;
using System.Reflection.Emit;

public class Example : MarshalByRefObject
{
   static void Main()
   {
      // Prepare to create a new application domain.
      AppDomainSetup setup = new AppDomainSetup();

      // Set the application name before setting the dynamic base.
      setup.ApplicationName = "Example";

      // Set the location of the base directory where assembly resolution
      // probes for dynamic assemblies. Note that the hash code of the
      // application name is concatenated to the base directory name you
      // supply.
      setup.DynamicBase = "C:\\DynamicAssemblyDir";
      Console.WriteLine("DynamicBase is set to '{0}'.", setup.DynamicBase);

      AppDomain ad = AppDomain.CreateDomain("MyDomain", null, setup);

      // The dynamic directory name is the dynamic base concatenated with
      // the application name: <DynamicBase>\<hash code>\<ApplicationName>
      string dynamicDir = ad.DynamicDirectory;
      Console.WriteLine("Dynamic directory is '{0}'.", dynamicDir);

      // The AssemblyBuilder won't create this directory automatically.
      if (!System.IO.Directory.Exists(dynamicDir))
      {
         Console.WriteLine("Creating the dynamic directory.");
         System.IO.Directory.CreateDirectory(dynamicDir);
      }

      // Generate a dynamic assembly and store it in the dynamic
      // directory.
      GenerateDynamicAssembly(dynamicDir);

      // Create an instance of the Example class in the application domain,
      // and call its Test method to load the dynamic assembly and use it.
      Example ex = (Example) ad.CreateInstanceAndUnwrap(
         typeof(Example).Assembly.FullName, "Example");
      ex.Test();
   }

   public void Test()
   {
      Assembly dynAssem = Assembly.Load(
         "DynamicHelloWorld, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");

      Type myType = dynAssem.GetType("HelloWorld");
      myType.InvokeMember("HelloFromAD", BindingFlags.Public |
         BindingFlags.Static | BindingFlags.InvokeMethod,
         Type.DefaultBinder, null, null);
   }

   private static void GenerateDynamicAssembly(string location)
   {
      // Define the dynamic assembly and the module. There is only one
      // module in this assembly. Note that the call to DefineDynamicAssembly
      // specifies the location where the assembly will be saved. The
      // assembly version is 1.0.0.0.
      //
      AssemblyName asmName = new AssemblyName("DynamicHelloWorld");
      asmName.Version = new Version("1.0.0.0");

      AssemblyBuilder ab =
         AppDomain.CurrentDomain.DefineDynamicAssembly(
            asmName, AssemblyBuilderAccess.Save, location);

      String moduleName = asmName.Name + ".exe";
      ModuleBuilder mb = ab.DefineDynamicModule(asmName.Name, moduleName);

      // Define the "HelloWorld" type, with one static method.
      TypeBuilder tb = mb.DefineType("HelloWorld", TypeAttributes.Public);
      MethodBuilder hello = tb.DefineMethod("HelloFromAD",
         MethodAttributes.Public | MethodAttributes.Static, null, null);

      // The method displays a message that contains the name of the application
      // domain where the method is executed.
      ILGenerator il = hello.GetILGenerator();
      il.Emit(OpCodes.Ldstr, "Hello from '{0}'!");
      il.Emit(OpCodes.Call, typeof(AppDomain).GetProperty("CurrentDomain").GetGetMethod());
      il.Emit(OpCodes.Call, typeof(AppDomain).GetProperty("FriendlyName").GetGetMethod());
      il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine",
                             new Type[] { typeof(String), typeof(String) }));
      il.Emit(OpCodes.Ret);

      // Complete the HelloWorld type and save the assembly. The assembly
      // is placed in the location specified by DefineDynamicAssembly.
      Type myType = tb.CreateType();
      ab.Save(moduleName);
   }
}

/* This example produces output similar to the following:

DynamicBase is set to 'C:\DynamicAssemblyDir\5e4a7545'.
Dynamic directory is 'C:\DynamicAssemblyDir\5e4a7545\Example'.
Creating the dynamic directory.
Hello from 'MyDomain'!
 */
Imports System.Reflection
Imports System.Reflection.Emit

Public Class Example 
   Inherits MarshalByRefObject
   
   Shared Sub Main(args() As String)

      ' Prepare to create a new application domain.
      Dim setup As New AppDomainSetup()

      ' Set the application name before setting the dynamic base.
      setup.ApplicationName = "Example"
      
      ' Set the location of the base directory where assembly resolution 
      ' probes for dynamic assemblies. Note that the hash code of the 
      ' application name is concatenated to the base directory name you 
      ' supply. 
      setup.DynamicBase = "C:\DynamicAssemblyDir"
      Console.WriteLine("DynamicBase is set to '{0}'.", setup.DynamicBase)

      Dim ad As AppDomain = AppDomain.CreateDomain("MyDomain", Nothing, setup)
      
      ' The dynamic directory name is the dynamic base concatenated with
      ' the application name: <DynamicBase>\<hash code>\<ApplicationName>
      Dim dynamicDir As String = ad.DynamicDirectory 
      Console.WriteLine("Dynamic directory is '{0}'.", dynamicDir)

      ' The AssemblyBuilder won't create this directory automatically.
      If Not System.IO.Directory.Exists(dynamicDir) Then 
         Console.WriteLine("Creating the dynamic directory.")
         System.IO.Directory.CreateDirectory(dynamicDir)
      End If

      ' Generate a dynamic assembly and store it in the dynamic 
      ' directory.
      GenerateDynamicAssembly(dynamicDir) 

      ' Create an instance of the Example class in the application domain,
      ' and call its Test method to load the dynamic assembly and use it.  
      Dim ex As Example = CType( _
         ad.CreateInstanceAndUnwrap( _
            GetType(Example).Assembly.FullName, "Example"), Example)
      ex.Test()
   End Sub

   Public Sub Test() 

      Dim dynAssem As [Assembly] = Assembly.Load(
         "DynamicHelloWorld, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")

      Dim myType As Type = dynAssem.GetType("HelloWorld")
      myType.InvokeMember("HelloFromAD", BindingFlags.Public Or _
         BindingFlags.Static Or BindingFlags.InvokeMethod, _
         Type.DefaultBinder, Nothing, Nothing) 'New Object() {})
   End Sub


   Private Shared Sub GenerateDynamicAssembly(ByVal location As String)
      
      ' Define the dynamic assembly and the module. There is only one
      ' module in this assembly. Note that the call to DefineDynamicAssembly 
      ' specifies the location where the assembly will be saved. The 
      ' assembly version is 1.0.0.0.
      '
      Dim asmName As New AssemblyName("DynamicHelloWorld")
      asmName.Version = New Version("1.0.0.0")

      Dim ab As AssemblyBuilder = _
         AppDomain.CurrentDomain.DefineDynamicAssembly( _
            asmName, AssemblyBuilderAccess.Save, location)

      Dim moduleName As String = asmName.Name & ".dll"
      Dim mb As ModuleBuilder = ab.DefineDynamicModule(asmName.Name, moduleName)
      
      ' Define the "HelloWorld" type, with one static method.
      Dim tb As TypeBuilder = mb.DefineType("HelloWorld", TypeAttributes.Public)
      Dim hello As MethodBuilder = tb.DefineMethod("HelloFromAD", _
         MethodAttributes.Public Or MethodAttributes.Static, Nothing, Nothing)

      ' The method displays a message that contains the name of the application
      ' domain where the method is executed.
      Dim il As ILGenerator = hello.GetILGenerator()
      il.Emit(OpCodes.Ldstr, "Hello from '{0}'!")
      il.Emit(OpCodes.Call, GetType(AppDomain).GetProperty("CurrentDomain").GetGetMethod())
      il.Emit(OpCodes.Call, GetType(AppDomain).GetProperty("FriendlyName").GetGetMethod())
      il.Emit(OpCodes.Call, GetType(Console).GetMethod("WriteLine", _
                             New Type() { GetType(String), GetType(String) }))
      il.Emit(OpCodes.Ret)

      ' Complete the HelloWorld type and save the assembly. The assembly
      ' is placed in the location specified by DefineDynamicAssembly.
      Dim myType As Type = tb.CreateType()
      ab.Save(moduleName)
   End Sub
End Class 

' This example produces output similar to the following:
'
'DynamicBase is set to 'C:\DynamicAssemblyDir\5e4a7545'.
'Dynamic directory is 'C:\DynamicAssemblyDir\5e4a7545\Example'.
'Creating the dynamic directory.
'Hello from 'MyDomain'!

備註

若要設定動態目錄,請將基底目錄路徑指派給 AppDomainSetup.DynamicBase AppDomainSetup 將用來建立新應用程式域的物件屬性。To set the dynamic directory, assign a base directory path to the AppDomainSetup.DynamicBase property of the AppDomainSetup object that will be used to create the new application domain. 您指派給屬性的基底目錄路徑是藉由新增子目錄,其簡單名稱是您指派給屬性之字串的雜湊碼 AppDomainSetup.ApplicationName ,因此基底目錄的格式為 原始路徑 \ 雜湊碼The base directory path you assign to the property is modified by the addition of a subdirectory whose simple name is the hash code of the string you assign to the AppDomainSetup.ApplicationName property, so the format of the base directory is original path\hash code. 動態目錄是此基底目錄的子目錄。The dynamic directory is a subdirectory of this base directory. 其簡單名稱是屬性的值 AppDomainSetup.ApplicationName ,因此其格式為 原始路徑 \ 雜湊碼 \ 應用程式名稱Its simple name is the value of the AppDomainSetup.ApplicationName property, so its format is original path\hash code\application name.

適用於