• 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());
    
  • 相关阅读:
    layui表格数据统计
    浅谈权限控制
    搜索栏实时更新查找内容
    虚拟域名
    关于阿里云服务器安装了Apache开放80端口访问不了网页
    验证码思路
    计算标准差 Exercise07_11
    倒置数组 Exercise07_12
    找出最小元素的下标 Exercise07_10
    找出最小元素 Exercise07_09
  • 原文地址:https://www.cnblogs.com/wxb8/p/12389896.html
Copyright © 2020-2023  润新知