SerializationFallbackBinder.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Runtime.Serialization;
  6. namespace PaintDotNet.SystemLayer
  7. {
  8. /// <summary>
  9. /// This is an implementation of SerializationBinder that tries to find a match
  10. /// for a type even if a direct match doesn't exist. This gets around versioning
  11. /// mismatches, and allows you to move data types between assemblies.
  12. /// </summary>
  13. /// <remarks>
  14. /// This class is in SystemLayer because there is code in this assembly that must
  15. /// make use of it. This class does not otherwise need to be here, and can be
  16. /// ignored by implementors.
  17. /// </remarks>
  18. public sealed class SerializationFallbackBinder
  19. : SerializationBinder
  20. {
  21. private List<Assembly> assemblies;
  22. public SerializationFallbackBinder()
  23. {
  24. this.assemblies = new List<Assembly>();
  25. }
  26. public void AddAssembly(Assembly assembly)
  27. {
  28. this.assemblies.Add(assembly);
  29. }
  30. private Type TryBindToType(Assembly assembly, string typeName)
  31. {
  32. Type type = assembly.GetType(typeName, false, true);
  33. return type;
  34. }
  35. public override Type BindToType(string assemblyName, string typeName)
  36. {
  37. Type type = null;
  38. foreach (Assembly tryAssembly in this.assemblies)
  39. {
  40. type = TryBindToType(tryAssembly, typeName);
  41. if (type != null)
  42. {
  43. break;
  44. }
  45. }
  46. if (type == null)
  47. {
  48. string fullTypeName = typeName + ", " + assemblyName;
  49. try
  50. {
  51. type = System.Type.GetType(fullTypeName, false, true);
  52. }
  53. catch (FileLoadException)
  54. {
  55. type = null;
  56. }
  57. }
  58. return type;
  59. }
  60. }
  61. }