Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

c# - 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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your current mechanism is very fragile - it won't work for signed assemblies (as the hash will change) or if you need to replace one resource with a larger one (as all the other offsets may move). It also has issues in terms of character encodings and the general mechanism to find the right point in the file anyway, but those are relatively unimportant given that I don't think the approach is appropriate to start with.

If you need replaceable resources, I'd put them in a different file altogether, which doesn't have the relatively delicate format of an assembly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...