Advertisement
Guest User

Untitled

a guest
Sep 18th, 2016
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.29 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.IO.Compression;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Web;
  15. using System.Web.Hosting;
  16. using System.Windows.Forms;
  17. using WinSCP;
  18.  
  19. namespace GameUpdater {
  20.     public partial class DownloadForm : Form {
  21.         private List<string> blacklist;
  22.         private string ftpServerIP;
  23.         private string ftpUserID;
  24.         private string ftpPassword;
  25.         private string mainUrl;
  26.         private WebClient client;
  27.         private long totalBytesXML = 0;  // TODO SET IN CONSTRUCTOR FROM XML FILE!!
  28.         private Queue<string> _downloadUrls = new Queue<string>();
  29.         private Queue<string> _downloadNmes = new Queue<string>();
  30.         private long totalBytesToDownload = 0;
  31.         private long downloadedData = 0;
  32.         private long dataDownloadedPerFile = 0;
  33.  
  34.         public DownloadForm(string ftpSrvrIP, string ftpUsrID, string ftpPswd, string url, List<string> bl, Icon programIco, long totalBytesOnServer) {
  35.             this.ftpServerIP = ftpSrvrIP;
  36.             this.ftpUserID = ftpUsrID;
  37.             this.ftpPassword = ftpPswd;
  38.             this.mainUrl = url;
  39.             this.blacklist = bl;
  40.             this.totalBytesToDownload = totalBytesOnServer;
  41.             InitializeComponent();
  42.             if(programIco != null)
  43.                 this.Icon = programIco;
  44.  
  45.             client = new WebClient();
  46.         }
  47.  
  48.         private void DownloadForm_Shown(object sender, EventArgs e) {
  49.             client.DownloadProgressChanged += client_DownloadProgressChanged;
  50.             client.DownloadFileCompleted += client_DownloadFileCompleted;
  51.             try {
  52.                     downloadURLs();
  53.             } catch (Exception ex){
  54.                 Console.WriteLine(ex);
  55.                 this.DialogResult = DialogResult.No;
  56.                 this.Close();
  57.             }
  58.         }
  59.  
  60.         private void downloadURLs() {
  61.             // prepare FTP connection
  62.             SessionOptions sessionOptions = new SessionOptions {
  63.                 Protocol = Protocol.Ftp,
  64.                 HostName = ftpServerIP,
  65.                 UserName = ftpUserID,
  66.                 Password = ftpPassword,
  67.             };
  68.  
  69.             Session session = new Session();
  70.  
  71.             // extract WinSCP.exe from resources to Temp folder
  72.             File.WriteAllBytes(Path.GetTempPath() + "\\WinSCP.exe", Properties.Resources.WinSCP);
  73.  
  74.             // open session
  75.             session.ExecutablePath = Path.GetTempPath() + "/WinSCP.exe";
  76.             session.Open(sessionOptions);
  77.  
  78.             // get all files into list
  79.             List<string> files = new List<string>();
  80.             RemoteDirectoryInfo list = session.ListDirectory("/");
  81.             foreach (RemoteFileInfo str in list.Files) {
  82.                 if (str.IsDirectory && !str.FullName.Contains("/..")) {
  83.                     Console.WriteLine("Entering folder " + str.FullName);
  84.                     files.AddRange(getFilesInSubfolder(session, session.ListDirectory(str.FullName)));
  85.                 } else if (!str.FullName.Contains("/..")) {
  86.                     files.Add(str.FullName);
  87.                     Console.WriteLine("Adding file " + str.FullName);
  88.                 }
  89.             }
  90.             session.Close();
  91.  
  92.             foreach (string str in files) {
  93.                 string[] fileNameParsed = str.Split('/');
  94.                 string fileName = fileNameParsed[fileNameParsed.Length - 1];
  95.                 Console.WriteLine("Current file: " + fileName);
  96.  
  97.                 if (!blacklist.Any(str.Contains)) { //check blacklist
  98.                     // create download url
  99.                     string urlDownload = HttpUtility.UrlPathEncode("http:/" + mainUrl + str);
  100.                     urlDownload = urlDownload.Replace("/web/", "/");
  101.                     Console.WriteLine("Download URL: " + urlDownload);
  102.  
  103.                     // create local location
  104.                     string location = @"D:\TEST2" + str.Replace(mainUrl, "").Replace('/', '\\');
  105.                     Console.WriteLine("Local path: " + location);
  106.  
  107.                     // create directory if doesn't exist
  108.                     if (!Directory.Exists(location.Replace(fileName, "")))
  109.                         Directory.CreateDirectory(location.Replace(fileName, ""));
  110.  
  111.                     // get file size of downloading file
  112.                     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlDownload);
  113.                     HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  114.                     long fileSizeDownload = response.ContentLength;
  115.                     response.Close();
  116.                     Console.WriteLine("File size: {0} bytes", fileSizeDownload);
  117.  
  118.                     // check if file exists and if size matches
  119.                     if (File.Exists(location)) {
  120.                         long localFileSize = new System.IO.FileInfo(location).Length;
  121.                         if (fileSizeDownload == localFileSize) {
  122.                             totalBytesXML -= localFileSize;
  123.                             continue;
  124.                         }
  125.                     }
  126.                     // download file
  127.                     if(totalBytesToDownload != -1)
  128.                         totalBytesToDownload += fileSizeDownload;
  129.  
  130.                     _downloadUrls.Enqueue(urlDownload);
  131.                     _downloadNmes.Enqueue(location);
  132.                 }
  133.             } //end foreach
  134.  
  135.             labelProgress.Text = String.Format("Downloaded {0} of {1} bytes", 0, totalBytesToDownload);
  136.             progressBar.Maximum = (int) (totalBytesToDownload + (totalBytesToDownload / 100 * 5));
  137.             labelDownloading.Text = "Downloading update ...";
  138.             downloadFiles();
  139.         }
  140.  
  141.         private void downloadFiles() {
  142.             if (_downloadUrls.Any()) {
  143.                 client = new WebClient();
  144.                 client.DownloadProgressChanged += client_DownloadProgressChanged;
  145.                 client.DownloadFileCompleted += client_DownloadFileCompleted;
  146.  
  147.                 var url = _downloadUrls.Dequeue();
  148.                 var filename = _downloadNmes.Dequeue();
  149.  
  150.                 client.DownloadFileAsync(new Uri(url), filename);
  151.                 return;
  152.             } else {
  153.                 progressBar.Value = progressBar.Maximum;
  154.                 labelProgress.Text = String.Format("Downloaded {0} of {1} bytes", totalBytesToDownload, totalBytesToDownload);
  155.                 Console.WriteLine("Download finished");
  156.                 Thread.Sleep(3);
  157.                 client.Dispose();
  158.                 this.Close();
  159.             }
  160.         }
  161.        
  162.         void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) {
  163.             labelProgress.Text = String.Format("Downloaded {0} of {1} bytes", downloadedData + e.BytesReceived, totalBytesToDownload);
  164.             dataDownloadedPerFile = e.BytesReceived;
  165.             progressBar.Value = (int)(downloadedData + e.BytesReceived);
  166.         }
  167.         void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
  168.             if (e.Error != null) {
  169.                 // handle error
  170.                 throw e.Error;
  171.             }
  172.             if (e.Cancelled) {
  173.                 // handle cancelled
  174.             }
  175.  
  176.             // continue downloading
  177.             downloadedData += dataDownloadedPerFile;
  178.             downloadFiles();
  179.         }
  180.  
  181.         // Recurse all subfolders and return path list
  182.         private List<string> getFilesInSubfolder(Session session, RemoteDirectoryInfo path) {
  183.             List<string> files = new List<string>();
  184.  
  185.             foreach (RemoteFileInfo str in path.Files) {
  186.                 if (str.IsDirectory && !str.FullName.Contains("/..")) {
  187.                     Console.WriteLine("Entering folder " + str.FullName);
  188.                     files.AddRange(getFilesInSubfolder(session, session.ListDirectory(str.FullName)));
  189.                 } else if (!str.FullName.Contains("/..")) {
  190.                     files.Add(str.FullName);
  191.                     Console.WriteLine("Adding file " + str.FullName);
  192.                 }
  193.             }
  194.  
  195.             return files;
  196.         }
  197.     }
  198. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement