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

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

问题描述

我正在开发一个插件主机.插件应该有尽可能少的信任,但是我希望插件有可能读取和写入文件.

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天全站免登陆