c# - How do I search for a type in .NET, disregarding the assembly version? -
i want maintain savefile compatibility between multiple versions of program, causes problems serialization, assembly qualified type name changes when increment version number, type.gettype() can't find it. there way search type disregarding assembly version?
whenever type not found assembyresolvedevent fired.
this event can used check types loaded , return type has same name ignore version number.
http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve%28v=vs.110%29.aspx
edit: time ago seems not recall correctly. adriano was correct. assemlyresolve ist asking assembly.
so additionally serializationbinder needed. sounds work, quite simple! i'll try summarize:
private static assembly currentdomain_assemblyresolve(object sender, resolveeventargs args) { if (args == null || string.isnullorempty(args.name)) return null; //if object serialized previous version .dll, deserialze current version .dll (only relevant strong names) foreach (assembly ass in appdomain.currentdomain.getassemblies()) { if ((args.name.startswith("xyz.")) // xyz marks namespace && args.name.contains("culture=neutral") && args.name.startswith(ass.fullname.split(',')[0])) return ass; } return null; }
remark: checks assemblies loaded!
your serializationbinder:
public class xyzserializationbinder : serializationbinder { public override type bindtotype(string assemblyname, string typename) { type curtype = null; //if object serialized previous version .dll, deserialze current version .dll (only relevant strong names) if (!string.isnullorempty(assemblyname) && assemblyname.contains("culture=neutral") && (assemblyname.startswith("xyz."))) { string plainassemblyname = assemblyname.split(',')[0]; assembly ass = assembly.load(plainassemblyname); curtype = ass.gettype(typename); } else { curtype = type.gettype(string.format("{0}, {1}", typename, assemblyname)); } if (curtype == null) { return typeof(invalidtype); } return curtype; } }
now use binder!
iformatter formatter = new binaryformatter(); formatter.binder = serializationbinder; using (filestream filestream = new filestream(filename, filemode.open, fileaccess.read, fileshare.read)) { storage = formatter.deserialize(filestream); }
i hope want / need!
Comments
Post a Comment