6

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.

ZedZip
  • 5,794
  • 15
  • 66
  • 119

3 Answers3

0

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

GregRos
  • 8,667
  • 3
  • 37
  • 63
0

You need to find the path your assemblies 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.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
usr
  • 168,620
  • 35
  • 240
  • 369
  • I cannot find paths because tehse assemblies are encrypted and in resources. App loads them on 'resolve event'. Property 'Location' unreadable because contain unprintable characters – ZedZip Jun 25 '12 at 08:24
0

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.

Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113
  • I tried this way in my test app (exe and my assembly). I tried to serialize my assembly. The error is on bformatter.Serialize() call: [System.Runtime.Serialization.SerializationException] = {"Type 'System.Runtime.Serialization.SerializationInfo' in Assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable."} – ZedZip Jun 25 '12 at 08:20