可以将一个应用程序域限制为一个目录吗? [英] Can an appdomain be restricted to one directory?

查看:79
本文介绍了可以将一个应用程序域限制为一个目录吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发插件主机.插件应该尽可能少地信任他们,但是我希望插件可以读写文件.

I am developing a plugin host. The plugins should have as little trust as they need, however I want to have the possibility for a plugin to read and write files.

是否可以限制将要加载程序集的AppDomain只能访问一个目录进行读写?

Can the AppDomain where the assembly will be loaded be restricted to have access to only one directory for reading and writing?

还可以理解其他选择和解决方法,例如,将文件数据从主机流传输到插件(读取)以及从插件流向主机(写入)的简单方法.

Other options and ways to go about this are also appreciated like for example easy ways to stream file data from the host to the plugin (reading) and from the plugin to the host (writing).

如果相关:我正在使用MAF基础结构的插件. http://msdn.microsoft.com/en-us/library/bb384200. aspx

If its relevant: I am using the MAF infrastructure for the plugins. http://msdn.microsoft.com/en-us/library/bb384200.aspx

推荐答案

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();
        }
    }
}

这篇关于可以将一个应用程序域限制为一个目录吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆