Download.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Runtime.InteropServices;
  7. using System.ServiceProcess;
  8. using System.Text;
  9. using System.IO;
  10. using System.Net;
  11. using WMI;
  12. using System.Xml;
  13. using System.Threading;
  14. using Microsoft.Win32;
  15. namespace winsw
  16. {
  17. /// <summary>
  18. /// Specify the download activities prior to the launch.
  19. /// This enables self-updating services.
  20. /// </summary>
  21. public class Download
  22. {
  23. public readonly string From;
  24. public readonly string To;
  25. internal Download(XmlNode n)
  26. {
  27. From = Environment.ExpandEnvironmentVariables(n.Attributes["from"].Value);
  28. To = Environment.ExpandEnvironmentVariables(n.Attributes["to"].Value);
  29. }
  30. public void Perform()
  31. {
  32. WebRequest req = WebRequest.Create(From);
  33. WebResponse rsp = req.GetResponse();
  34. FileStream tmpstream = new FileStream(To + ".tmp", FileMode.Create);
  35. CopyStream(rsp.GetResponseStream(), tmpstream);
  36. // only after we successfully downloaded a file, overwrite the existing one
  37. if (File.Exists(To))
  38. File.Delete(To);
  39. File.Move(To + ".tmp", To);
  40. }
  41. private static void CopyStream(Stream i, Stream o)
  42. {
  43. byte[] buf = new byte[8192];
  44. while (true)
  45. {
  46. int len = i.Read(buf, 0, buf.Length);
  47. if (len <= 0) break;
  48. o.Write(buf, 0, len);
  49. }
  50. i.Close();
  51. o.Close();
  52. }
  53. }
  54. }