XmlUrlResolver.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // System.Xml.XmlUrlResolver.cs
  2. //
  3. // Author: Duncan Mak ([email protected])
  4. // Atsushi Enomoto ([email protected])
  5. //
  6. // (C) Ximian, Inc.
  7. //
  8. using System.Net;
  9. using System.IO;
  10. using System.Text;
  11. namespace System.Xml
  12. {
  13. public class XmlUrlResolver : XmlResolver
  14. {
  15. // Field
  16. ICredentials credential;
  17. WebClient webClientInternal;
  18. WebClient webClient {
  19. get {
  20. if (webClientInternal == null)
  21. webClientInternal = new WebClient ();
  22. return webClientInternal;
  23. }
  24. }
  25. // Constructor
  26. public XmlUrlResolver ()
  27. : base ()
  28. {
  29. }
  30. // Properties
  31. public override ICredentials Credentials
  32. {
  33. set { credential = value; }
  34. }
  35. // Methods
  36. public override object GetEntity (Uri absoluteUri, string role, Type ofObjectToReturn)
  37. {
  38. if (ofObjectToReturn == null)
  39. ofObjectToReturn = typeof (Stream);
  40. if (ofObjectToReturn != typeof (Stream))
  41. throw new XmlException ("This object type is not supported.");
  42. if (absoluteUri.Scheme == "file") {
  43. if (absoluteUri.AbsolutePath == String.Empty)
  44. throw new ArgumentException ("uri must be absolute.", "absoluteUri");
  45. return new FileStream (UnescapeRelativeUriBody (absoluteUri.LocalPath), FileMode.Open, FileAccess.Read, FileShare.Read);
  46. }
  47. // (MS documentation says) parameter role isn't used yet.
  48. Stream s = null;
  49. using (s) {
  50. WebClient wc = new WebClient ();
  51. wc.Credentials = credential;
  52. byte [] data = wc.DownloadData (absoluteUri.ToString ());
  53. wc.Dispose ();
  54. return new MemoryStream (data, 0, data.Length);
  55. }
  56. }
  57. // see also XmlResolver.EscapeRelativeUriBody().
  58. private string UnescapeRelativeUriBody (string src)
  59. {
  60. return src.Replace ("%3C", "<")
  61. .Replace ("%3E", ">")
  62. .Replace ("%23", "#")
  63. .Replace ("%25", "%")
  64. .Replace ("%22", "\"");
  65. }
  66. }
  67. }