How to save assembly to disk?

我与影子孤独终老i 提交于 2020-01-03 17:07:29

问题


How I can save assembly to file? I.e. I mean not dynamic assembly but "normal" in-memory assemblies.

Assembly[] asslist = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly ass1 in asslist)
{
    // How to save?
}

This situation can occur when the application loads some referenced assemblies from resources. I want to save them to disk.

It is impossible to extract assemblies form resources because they are encrypted there.


回答1:


How about trying to serialize the assembly? It is serializable.




回答2:


You need to find the path your ass[...]es came from. You can find it like this:

Assembly ass = ...;
return ass.Location;

Notice, that as is a keyword and cannot be used as an identifier. I recommend using ass.




回答3:


From the idea of Greg Ros i developed this little snippet. Please note that i tried to stick to the naming conventions.

public void SaveAllAssemblies()
{   
    Assembly[] asslist = AppDomain.CurrentDomain.GetAssemblies();
    foreach (Assembly ass in asslist)
    {
        FileInfo fi = new FileInfo(ass.Location);

        if (!fi.Extension.Equals(".exe", StringComparison.InvariantCultureIgnoreCase))
        {
            var assName = fi.Name;
            var assConverter = new FormatterConverter(); 
            var assInfo = new SerializationInfo(typeof(Assembly), assConverter);
            var assContext = new StreamingContext();

            using (var assStream = new FileStream(assName, FileMode.Create))
            {
                BinaryFormatter bformatter = new BinaryFormatter();
                ass.GetObjectData(assInfo, assContext);

                bformatter.Serialize(assStream, assInfo);
                assStream.Close();
            }
        }
    }
}   

But some assemblies are not marked as serializable, as for example mscorlib.dll. Hence this is probably only a partial solution?

Despite that it is possible to serialize some assemblies, I suggest using the FileInfo as provided in the example, generate a list and inspect the original assemblies.



来源:https://stackoverflow.com/questions/11180391/how-to-save-assembly-to-disk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!