Can an appdomain be restricted to one directory?

老子叫甜甜 提交于 2019-12-05 06:49:50
namespace ConsoleApplication
{
    #region Imports

    using System;
    using System.IO;
    using System.Security;
    using System.Security.Permissions;

    #endregion

    public class Plugin : MarshalByRefObject
    {        
        public string TestRead(string path)
        {
            try
            {
                File.ReadAllBytes(path);
                return "Done";
            }
            catch (SecurityException)
            {
                return "Access Denied";
            }
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var setup = new AppDomainSetup();

            setup.ApplicationBase = 
                AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            var perm = new PermissionSet(PermissionState.None);

            perm.AddPermission(
                new SecurityPermission(
                    SecurityPermissionFlag.Execution));

            perm.AddPermission(
                new FileIOPermission(
                    FileIOPermissionAccess.Read, "c:\\public\\"));

            var pluginDomain = 
                AppDomain.CreateDomain("PluginDomain", null, setup, perm);

            var plugin = 
                pluginDomain.CreateInstanceAndUnwrap(
                    typeof(Plugin).Assembly.FullName,
                    typeof(Plugin).FullName) as Plugin;

            Console.WriteLine(plugin.TestRead("c:\\public\\test.txt"));
            Console.WriteLine(plugin.TestRead("c:\\secret\\test.txt"));
            Console.ReadKey();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!