Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically embed resources in a .NET assembly

I have a compiled .NET assembly with a specific resource file embedded (named 'Script.xml'). I need to programmatically change it out for another.

Is this possible to do without recompiling from source?

Currently, I do a search for text I know is in the file and it works well. But I need to do it for another project where I don't know any of the contents of the resource file and I need to find another method.

FileStream exe = new FileStream(currentexe, FileMode.Open);

//find xml part of exefile
string find = "<?xml version=\"1.0\"?>";
string lastchars = new string(' ', find.Length);
while (exe.CanRead) {
    lastchars = lastchars.Substring(1) + (char)exe.ReadByte();
    if (lastchars == find) {
        exe.Seek(-find.Length, SeekOrigin.Current);
        break;
    }
}

//output serialized script
int bytenum = 0;
foreach (byte c in xml) {
    if (c == 0) break;
    exe.WriteByte(c);
    bytenum++;
}

//clean out extra data
while (bytenum++ < ScriptFileSize) {
    exe.WriteByte(0x20);
}
exe.Close();
like image 358
Nick Whaley Avatar asked Jul 10 '09 05:07

Nick Whaley


People also ask

How do you add an embedded resource?

Open Solution Explorer add files you want to embed. Right click on the files then click on Properties . In Properties window and change Build Action to Embedded Resource . After that you should write the embedded resources to file in order to be able to run it.

What is resources in assembly in. net?

The ResourceSet class, which enables you to retrieve the resources of a specific culture without observing fallback rules. The resources can be stored in an assembly or a standalone binary . resources file.


1 Answers

You could use Cecil to open the assembly and insert a resource (I do). YMMV

like image 83
Anton Tykhyy Avatar answered Nov 03 '22 01:11

Anton Tykhyy