zoukankan      html  css  js  c++  java
  • C# wpf,winform修改另一个.net EXE程序集的resources 资源文件

    可以使用Mono.Cecil库更新、添加可执行文件的资源
    以下是使用 Mono.Cecil 进行资源操作的三种基本方法:

    首先需要程序中引入 Mono.Cecil
    Nuget:
    PM> Install-Package Mono.Cecil
    

    三种方法

    public static void ReplaceResource(string path, string resourceName, byte[] resource)
    {
        var definition =
            AssemblyDefinition.ReadAssembly(path);
    
        for (var i = 0; i < definition.MainModule.Resources.Count; i++)
            if (definition.MainModule.Resources[i].Name == resourceName)
            {
                definition.MainModule.Resources.RemoveAt(i);
                break;
            }
    
        var er = new EmbeddedResource(resourceName, ManifestResourceAttributes.Public, resource);
        definition.MainModule.Resources.Add(er);
        definition.Write(path);
    }
    
    public static void AddResource(string path, string resourceName, byte[] resource)
    {
        var definition =
            AssemblyDefinition.ReadAssembly(path);
    
        var er = new EmbeddedResource(resourceName, ManifestResourceAttributes.Public, resource);
        definition.MainModule.Resources.Add(er);
        definition.Write(path);
    }
    
    public static MemoryStream GetResource(string path, string resourceName)
    {
        var definition =
            AssemblyDefinition.ReadAssembly(path);
    
        foreach (var resource in definition.MainModule.Resources)
            if (resource.Name == resourceName)
            {
                var embeddedResource =(EmbeddedResource) resource;
                var stream = embeddedResource.GetResourceStream();
    
                var bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
    
                var memStream = new MemoryStream();
                memStream.Write(bytes,0,bytes.Length);
                memStream.Position = 0;
                return memStream;
            }
    
        return null;
    }
    

    您可以读取/写入或修改当前资源或创建新资源,然后只需通过调用 或添加它作为新资源调用即可将其放回可执行文件ResourceWriter、ResourceReader、ResourceEditor

    下面是替换资源中的图像的示例

    var ms = new MemoryStream();
    var writer = new ResourceWriter(ms);
    writer.AddResource("good_luck",new Bitmap("good_luck.png"));
    writer.Generate();   
    ReplaceResource(@"my executale.exe", "ResourceTest.Properties.Resources.resources",ms.ToArray());
    
  • 相关阅读:
    转: CEF嵌入到单文档mfc
    浅谈C++多态性
    C++面试整理1
    面试汇总
    【转】一些经典的笔试题
    C# 委托
    搭建Nuget
    thinkphp框架之模型(数据库查询)
    利用csc.exe 手动编译C#程序
    css
  • 原文地址:https://www.cnblogs.com/wxb8/p/12389896.html
Copyright © 2011-2022 走看看