XmlUrlResolver.cs 1.9 KB

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