Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Diagnostics;
- using System.Drawing;
- using System.IO;
- using System.IO.Compression;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Hosting;
- using System.Windows.Forms;
- using WinSCP;
- namespace GameUpdater {
- public partial class DownloadForm : Form {
- private List<string> blacklist;
- private string ftpServerIP;
- private string ftpUserID;
- private string ftpPassword;
- private string mainUrl;
- private WebClient client;
- private long totalBytesXML = 0; // TODO SET IN CONSTRUCTOR FROM XML FILE!!
- private Queue<string> _downloadUrls = new Queue<string>();
- private Queue<string> _downloadNmes = new Queue<string>();
- private long totalBytesToDownload = 0;
- private long downloadedData = 0;
- private long dataDownloadedPerFile = 0;
- public DownloadForm(string ftpSrvrIP, string ftpUsrID, string ftpPswd, string url, List<string> bl, Icon programIco, long totalBytesOnServer) {
- this.ftpServerIP = ftpSrvrIP;
- this.ftpUserID = ftpUsrID;
- this.ftpPassword = ftpPswd;
- this.mainUrl = url;
- this.blacklist = bl;
- this.totalBytesToDownload = totalBytesOnServer;
- InitializeComponent();
- if(programIco != null)
- this.Icon = programIco;
- client = new WebClient();
- }
- private void DownloadForm_Shown(object sender, EventArgs e) {
- client.DownloadProgressChanged += client_DownloadProgressChanged;
- client.DownloadFileCompleted += client_DownloadFileCompleted;
- try {
- downloadURLs();
- } catch (Exception ex){
- Console.WriteLine(ex);
- this.DialogResult = DialogResult.No;
- this.Close();
- }
- }
- private void downloadURLs() {
- // prepare FTP connection
- SessionOptions sessionOptions = new SessionOptions {
- Protocol = Protocol.Ftp,
- HostName = ftpServerIP,
- UserName = ftpUserID,
- Password = ftpPassword,
- };
- Session session = new Session();
- // extract WinSCP.exe from resources to Temp folder
- File.WriteAllBytes(Path.GetTempPath() + "\\WinSCP.exe", Properties.Resources.WinSCP);
- // open session
- session.ExecutablePath = Path.GetTempPath() + "/WinSCP.exe";
- session.Open(sessionOptions);
- // get all files into list
- List<string> files = new List<string>();
- RemoteDirectoryInfo list = session.ListDirectory("/");
- foreach (RemoteFileInfo str in list.Files) {
- if (str.IsDirectory && !str.FullName.Contains("/..")) {
- Console.WriteLine("Entering folder " + str.FullName);
- files.AddRange(getFilesInSubfolder(session, session.ListDirectory(str.FullName)));
- } else if (!str.FullName.Contains("/..")) {
- files.Add(str.FullName);
- Console.WriteLine("Adding file " + str.FullName);
- }
- }
- session.Close();
- foreach (string str in files) {
- string[] fileNameParsed = str.Split('/');
- string fileName = fileNameParsed[fileNameParsed.Length - 1];
- Console.WriteLine("Current file: " + fileName);
- if (!blacklist.Any(str.Contains)) { //check blacklist
- // create download url
- string urlDownload = HttpUtility.UrlPathEncode("http:/" + mainUrl + str);
- urlDownload = urlDownload.Replace("/web/", "/");
- Console.WriteLine("Download URL: " + urlDownload);
- // create local location
- string location = @"D:\TEST2" + str.Replace(mainUrl, "").Replace('/', '\\');
- Console.WriteLine("Local path: " + location);
- // create directory if doesn't exist
- if (!Directory.Exists(location.Replace(fileName, "")))
- Directory.CreateDirectory(location.Replace(fileName, ""));
- // get file size of downloading file
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlDownload);
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- long fileSizeDownload = response.ContentLength;
- response.Close();
- Console.WriteLine("File size: {0} bytes", fileSizeDownload);
- // check if file exists and if size matches
- if (File.Exists(location)) {
- long localFileSize = new System.IO.FileInfo(location).Length;
- if (fileSizeDownload == localFileSize) {
- totalBytesXML -= localFileSize;
- continue;
- }
- }
- // download file
- if(totalBytesToDownload != -1)
- totalBytesToDownload += fileSizeDownload;
- _downloadUrls.Enqueue(urlDownload);
- _downloadNmes.Enqueue(location);
- }
- } //end foreach
- labelProgress.Text = String.Format("Downloaded {0} of {1} bytes", 0, totalBytesToDownload);
- progressBar.Maximum = (int) (totalBytesToDownload + (totalBytesToDownload / 100 * 5));
- labelDownloading.Text = "Downloading update ...";
- downloadFiles();
- }
- private void downloadFiles() {
- if (_downloadUrls.Any()) {
- client = new WebClient();
- client.DownloadProgressChanged += client_DownloadProgressChanged;
- client.DownloadFileCompleted += client_DownloadFileCompleted;
- var url = _downloadUrls.Dequeue();
- var filename = _downloadNmes.Dequeue();
- client.DownloadFileAsync(new Uri(url), filename);
- return;
- } else {
- progressBar.Value = progressBar.Maximum;
- labelProgress.Text = String.Format("Downloaded {0} of {1} bytes", totalBytesToDownload, totalBytesToDownload);
- Console.WriteLine("Download finished");
- Thread.Sleep(3);
- client.Dispose();
- this.Close();
- }
- }
- void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) {
- labelProgress.Text = String.Format("Downloaded {0} of {1} bytes", downloadedData + e.BytesReceived, totalBytesToDownload);
- dataDownloadedPerFile = e.BytesReceived;
- progressBar.Value = (int)(downloadedData + e.BytesReceived);
- }
- void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
- if (e.Error != null) {
- // handle error
- throw e.Error;
- }
- if (e.Cancelled) {
- // handle cancelled
- }
- // continue downloading
- downloadedData += dataDownloadedPerFile;
- downloadFiles();
- }
- // Recurse all subfolders and return path list
- private List<string> getFilesInSubfolder(Session session, RemoteDirectoryInfo path) {
- List<string> files = new List<string>();
- foreach (RemoteFileInfo str in path.Files) {
- if (str.IsDirectory && !str.FullName.Contains("/..")) {
- Console.WriteLine("Entering folder " + str.FullName);
- files.AddRange(getFilesInSubfolder(session, session.ListDirectory(str.FullName)));
- } else if (!str.FullName.Contains("/..")) {
- files.Add(str.FullName);
- Console.WriteLine("Adding file " + str.FullName);
- }
- }
- return files;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement