【问题标题】:add assembly from resources with ResourceManager使用 ResourceManager 从资源中添加程序集
【发布时间】:2014-01-17 20:09:40
【问题描述】:

我想用 ResourceManager 添加一个程序集 我有这段代码,但它显然不起作用。请帮忙!

加载资源并尝试将其用作程序集:

  static ResourceManager resourceManager = new ResourceManager("res", Assembly.GetExecutingAssembly());

  static void Main()
  {
     AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  }

  static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  {
     AppDomain domain = (AppDomain)sender;
     if(args.Name.Contains("System.Data.SQLite"))
     {
        return domain.Load(resourceManager.GetObject("System.Data.SQLite"));
     }
     return null;
  }

将资源放入 ResourceManager:

        using (ResourceWriter w = new ResourceWriter("res.resources"))
        {
           w.AddResource("System.Data.SQLite", File.ReadAllText("System.Data.SQLite.dll"));
        }

        if (CodeDom.Compile(outputValueTb.Text, Properties.Resources.src, iconValueTb.Text, "res.resources"))
        {
           //File.Copy("System.Data.SQLite.dll", System.IO.Path.GetDirectoryName(outputValueTb.Text) + "/System.Data.SQLite.dll");
           File.Delete("res.resources");
           success("Built");
        }

编辑

所以我把我的代码改成了这个

w.AddResource("System.Data.SQLite", File.ReadAllBytes("System.Data.SQLite.dll"));

但我仍然不知道如何使用此代码将资源用于程序集:

     AppDomain domain = (AppDomain)sender;
     if(args.Name.Contains("System.Data.SQLite"))
     {
        return domain.Load(resourceManager.GetObject("System.Data.SQLite")); //should be a resource not bytes[] 
     }
     return null;

【问题讨论】:

  • 为什么用 File.ReadAllText 读取二进制文件? DLL 不是文本文件。请改用 File.ReadAllBytes(并调整您的代码,以便处理返回的字节数组)
  • 如何“调整你的代码以便处理返回的字节数组”
  • 您的问题“如何”是什么意思?您的意思是,您不知道如何将字节数组资源添加到资源文件中?
  • 不知道如何处理返回的字节数组
  • 您能否更具体地说明您的问题是关于字节数组(和资源)的问题

标签: c# resources codedom


【解决方案1】:

如果您已将 dll 添加为项目项文件并在 Build Action 类型(属性下)上将其标记为“Embedded Resource”,则可以使用以下内容。 Resolver 是您已经拥有的事件处理程序。注意:我没有检查语法,只是在这里输入;因此,如果需要,请修复语法。

internal static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
   var name = Assembly.GetExecutingAssembly()
                 .GetManifestResourceNames()
                 .FirstOrDefault(f => f.Contains("System.Data.SQLite"));

   if (!string.IsNullOrEmpty(name) && args.Name.Contains("SQLite")) 
   {
    using(var strm = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
    {
      var bytes = new byte[strm.Length];
      stream.Read(bytes, 0, strm.Length);
      return Assembly.Load(bytes);
    }   
   }
   return null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多