这是我的代码:
System.Security.PermissionSet PS = new System.Security.PermissionSet(PermissionState.None);
PS.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess,Path));
PS.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
AppDomainSetup ADS = new AppDomainSetup();
ADS.ApplicationBase= Path;
AppDomain domain = AppDomain.CreateDomain("Pluging", null, ADS, PS, null);
Assembly asm = Assembly.LoadFrom(Path + "MacroBase.dll");
domain.Load(asm.FullName);
MacroBase.MacroBase em = (MacroBase.MacroBase)domain.CreateInstanceAndUnwrap(asm.FullName, "MacroBase.MacroBase");
em.Application(1);
参数Path具有包含dll的floder的地址。现在是 “D:\ Programming Projects \ Server3 \ Macros \ c7b465b2-8314-4c7e-be3c-10c0185b4ac6” 一个macrobase.dll的副本在Guid文件夹中。 Appdomain加载此dll并运行方法Application。
我希望最后一行不能访问c:\,因为在开头应用的FileIOPermissionAccess,但提到的方法:
MacroBase.Application(int i)
{
System.IO.File.ReadAllBytes("c:\\test1_V.103.xls");
}
就像完全不受限制一样运行。
基于Microsoft的这篇文章: How to: Run Partially Trusted Code in a Sandbox 我也尝试了以下格式,没有更好的结果(它可以访问c:):
System.Security.PermissionSet PS = new System.Security.PermissionSet(PermissionState.None);
PS.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess,Path));
PS.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
AppDomainSetup ADS = new AppDomainSetup();
ADS.ApplicationBase= Path;
AppDomain domain = AppDomain.CreateDomain("Pluging", null, ADS, PS, null);
Assembly asm = Assembly.LoadFrom(Path + "MacroBase.dll");
domain.Load(asm.FullName);
System.Runtime.Remoting.ObjectHandle handle = Activator.CreateInstanceFrom(domain, Path + "MacroBase.dll", "MacroBase.MacroBase");
MacroBase.MacroBase m = (MacroBase.MacroBase)handle.Unwrap();
m.Application(1);
MacroBase.Macrobase是未来宏的占位符。它被放在一个名为macrobase.dll的dll中。现在它只包含一些虚拟代码:
namespace MacroBase
{
[Serializable]
public class MacroBase
{
public void Application(int i)
{
List<int> i1 = new System.Collections.Generic.List<int>() { 1,2,3,4};
System.IO.File.ReadAllBytes("c:\\test1_V.103.xls");
switch(i)
{
case 0:
break;
case 1:
break;
default:
break;
}
}
}
}
答案 0 :(得分:6)
您的类标记为[Serializable]
并且不是从MarshalByRefObject
派生的,这意味着当实例通过应用程序域边界时,它会被序列化,而不是在目标域中反序列化。因此,您的代码将在当前域中执行,而不是在单独的域中执行。您应该从MacroBase.Macrobase
派生MarshalByRefObject
类,以使代码在单独的域中执行。