问题
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