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());
posted @ 2020-03-01 15:07  Monns  阅读(1443)  评论(1编辑  收藏  举报