آموزش C# - 2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
public class QRapidDownloder
{
public List
public bool SkipOnError { get; set; }
public string username
{
get { return Username; }
set { Username = value; }
}
public string password
{
get { return Password; }
set { Password = value; }
}
public string SaveDirectory
{
get { return FileDirectory; }
set { FileDirectory = value; }
}
private string Username;
private string Password;
private string FileDirectory;
private int OnlineJobs;
public List
public delegate void ChangedEventHandler(int ID, string Message);
public delegate void ProgressChangedEventHandler(int ID, int Percent);
public delegate void AllChangedEventHandler(string Message);
public event ChangedEventHandler onChanged;
public event ChangedEventHandler onError;
public event ChangedEventHandler onCompleted;
public event AllChangedEventHandler onAllCompleted;
public event ProgressChangedEventHandler onProgressChanged;
public class QDownloadParam
{
public int ID;
public string Link;
public string Username;
public string Password;
public string FileDirectory;
public BackgroundWorker Worker;
public string FileName;
public string Status;
public int Progress;
}
public QRapidDownloder()
{
SkipOnError = false;
}
// Invoke the Changed event; called whenever list changes:
protected virtual void OnChanged(int ID, string Message)
{
if (onChanged != null)
onChanged(ID, Message);
}
protected virtual void OnError(int ID, string Message)
{
if (onError != null)
onError(ID, Message);
}
protected virtual void OnCompleted(int ID, string Message)
{
if (onCompleted != null)
onCompleted(ID, Message);
}
protected virtual void OnAllCompleted(string Message)
{
if (onAllCompleted != null)
onAllCompleted(Message);
}
protected virtual void OnProgressChanged(int ID, int Percent)
{
if (onProgressChanged != null)
onProgressChanged(ID, Percent);
}
///
/// Start to Download all the Links in Link List at the same time.
///
public void StartAll()
{
int i = 0;
foreach (var link in Links)
{
try
{
var uri = new Uri(link);
}
catch (Exception exception)
{
OnError(i, "Error: Job ID(" + i + ") " + exception.Message);
i++;
continue;
}
var backgroundWorker = new BackgroundWorker() { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
backgroundWorker.DoWork += (backgroundWorker_DoWork);
backgroundWorker.ProgressChanged += (backgroundWorker_ProgressChanged);
backgroundWorker.RunWorkerCompleted += (backgroundWorker_RunWorkerCompleted);
var downloadParam = new QDownloadParam() { ID = i, FileDirectory = FileDirectory, Link = link, Password = Password, Username = Username, Worker = backgroundWorker };
Jobs.Add(downloadParam);
OnChanged(i, "Job ID(" + i + ") Added.");
backgroundWorker.RunWorkerAsync(downloadParam);
i++;
}
OnlineJobs = Jobs.Count;
}
///
/// Cancel All Downloads.
///
///
public int CancelAll()
{
int i = 0;
foreach (var job in Jobs)
{
try
{
job.Worker.CancelAsync();
}
catch (Exception exception)
{
OnError(i, "Error: " + exception.Message);
}
i++;
}
return i;
}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//button2.Enabled = false;
//listBox1.Items.Insert(0, e.Result.ToString());
var Param = (QDownloadParam)e.Result;
OnCompleted(Param.ID, "Job(" + Param.ID + ") Complete.");
OnlineJobs--;
if (OnlineJobs <= 0)
{
OnAllCompleted("All Finish!");
}
}
void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var param = (QDownloadParam)e.UserState;
switch (e.ProgressPercentage)
{
case -1:
OnError(param.ID, param.Status); break;
case 1:
OnChanged(param.ID, param.Status); break;
case 2:
OnProgressChanged(param.ID, param.Progress); break;
}
}
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var Param = (QDownloadParam)e.Argument;
e.Result = QDownload(Param);
}
///
/// Start Download and Report Progress
///
///
///
private QDownloadParam QDownload(QDownloadParam param)
{
param.Status = "Connecting... (" + param.Link + ")";
param.Worker.ReportProgress(1, param);
var URL = new Uri(param.Link.Trim());
var req = (HttpWebRequest)WebRequest.Create(URL);
req.AllowAutoRedirect = true;
if (!string.IsNullOrEmpty(param.Username))
{
byte[] authBytes = Encoding.UTF8.GetBytes((param.Username + ":" + param.Password).ToCharArray());
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);
}
req.MaximumAutomaticRedirections = 100;
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
req.Accept = "*/*";
req.KeepAlive = true;
req.Timeout = 9999999; //prefRequestTimeout
req.CookieContainer = GetUriCookieContainer(URL.AbsoluteUri);
// Get the stream from the returned web response
HttpWebResponse webresponse = null;
try
{
webresponse = (HttpWebResponse)req.GetResponse();
if (webresponse.ResponseUri.AbsoluteUri != URL.AbsoluteUri)
{
param.Link = webresponse.ResponseUri.AbsoluteUri;
param.Status = "Redirecting... (" + param.Link + ")";
param.Worker.ReportProgress(1, param);
QDownload(param); return param;
}
param.Status = "Connected. (" + param.Link + ")";
param.Worker.ReportProgress(1, param);
}
catch (WebException e)
{
param.Status = "error: " + e;
param.Worker.ReportProgress(-1, param);
return param;
}
try
{
var file = Path.GetFileName(webresponse.ResponseUri.AbsoluteUri);
if (!webresponse.ContentType.Contains("text/html"))
{
file = file.Replace(".html", "");
}
else
{
param.Status = "Check the Username or Password!";
param.Worker.ReportProgress(-1, param);
if (SkipOnError)
{
param.Status = "Download Skip. " + param.Link;
return param;
}
}
param.FileName = file;
param.Status = "Downloading File: " + file + "(" + (webresponse.ContentLength / 1000) + "KB)";
param.Worker.ReportProgress(1, param);
string filepath;
if (param.FileDirectory.EndsWith("\\")) filepath = param.FileDirectory + file;
else
{
filepath = param.FileDirectory + "\\" + file;
}
var writeStream = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite);
var readStream = webresponse.GetResponseStream();
try
{
const int Length = 256;
var buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
if (param.Worker.CancellationPending) return param;
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
int Percent = (int)((writeStream.Length * 100) / webresponse.ContentLength);
param.Progress = Percent;
param.Worker.ReportProgress(2, param);
}
readStream.Close();
writeStream.Close();
}
catch (Exception exception)
{
param.Status = "error: " + exception;
param.Worker.ReportProgress(-1, param);
return param;
}
param.Status = "Download Finish: " + file;
param.Worker.ReportProgress(1, param);
}
catch (Exception exception)
{
param.Status = "error: " + exception;
param.Worker.ReportProgress(-1, param);
return param;
}
return param;
}
private static CookieContainer GetUriCookieContainer(string uri)
{
CookieContainer cookies = new CookieContainer();
foreach (Cookie c in CookieManager.GetCookie(uri))
cookies.SetCookies(new Uri(uri), c.ToString());
return cookies;
}
class CookieManager
{
public class CookieStruct
{
//1 The Variable Name
//2 The Value for the Variable
//3 The Website of the Cookie’s Owner
//4 Optional Flags
//5 The Most Significant Integer for Expired Time, in FILETIME Format
//6 The Least Significant Integer for Expired Time, in FILETIME Format
//7 The Most Significant Integer for Creation Time, in FILETIME Format
//8 The Least Significant Integer for Creation Time, in FILETIME Format
//9 The Cookie Record Delimiter (a * character)
public string VarName;
public string VarValue;
public string Domain;
public int Flags;
public DateTime ExpirationDate;
public DateTime CreationDate;
}
public static CookieCollection GetCookie(string url)
{
CookieCollection ret = new CookieCollection();
url = url.Remove(0, 7);
string baseUrl;
if (url.IndexOf("/") > 0) baseUrl = url.Substring(0, url.IndexOf("/")); else baseUrl = url;
baseUrl += "/";
string Domain = baseUrl;
Domain = Domain.Substring(0, Domain.LastIndexOf('.'));
while (Domain.IndexOf('.') > -1)
Domain = Domain.Substring(Domain.IndexOf('.') + 1);
FileInfo[] fis = SearchCookies(Domain);
foreach (FileInfo fi in fis)
{
CookieStruct[] cs = ReadCookie(fi.FullName);
foreach (CookieStruct c in cs)
if (baseUrl.EndsWith(c.Domain) && c.ExpirationDate > DateTime.Now)
{
Cookie nc = new Cookie(c.VarName, c.VarValue);
nc.Expires = c.ExpirationDate;
nc.Domain = c.Domain;
ret.Add(nc);
}
}
return ret;
}
private static FileInfo[] SearchCookies(string Domain)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Cookies);
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] fis = di.GetFiles(string.Format("*@{0}[*.txt", Domain));
di = new DirectoryInfo(path + "//Low");
FileInfo[] fisLow = di.GetFiles(string.Format("*@{0}[*.txt", Domain));
FileInfo[] ret = new FileInfo[fis.Length + fisLow.Length];
fis.CopyTo(ret, 0);
fisLow.CopyTo(ret, fis.Length);
return ret;
}
private static CookieStruct[] ReadCookie(string fn)
{
StreamReader sr = new StreamReader(fn);
string cookie = sr.ReadToEnd();
sr.Close();
string[] data = cookie.Split('\n');
int cookieNum = data.Length / 9;
CookieStruct[] ret = new CookieStruct[cookieNum];
for (int i = 0; i < cookieNum; i++)
{
int bline = i * 9;
ret[i] = new CookieStruct();
ret[i].VarName = data[bline];
ret[i].VarValue = data[bline + 1];
ret[i].Domain = data[bline + 2];
ret[i].Flags = Convert.ToInt32(data[bline + 3]);
long l = Convert.ToInt64(data[bline + 4]);
l += Convert.ToInt64(data[bline + 5]) << 32;
ret[i].ExpirationDate = DateTime.FromFileTime(l);
l = Convert.ToInt64(data[bline + 6]);
l += Convert.ToInt64(data[bline + 7]) << 32;
ret[i].CreationDate = DateTime.FromFileTime(l);
}
return ret;
}
}
}
اينم يه نمونه نحوه استفاده از اين كلاس:
private QRapidDownloder rapidDownloder;
rapidDownloder = new QRapidDownloder
{
username = textBox1.Text,
password = textBox2.Text,
SaveDirectory = textBox3.Text
};
rapidDownloder.onChanged += (rapidDownloder_onChanged);
rapidDownloder.onCompleted += (rapidDownloder_onCompleted);
rapidDownloder.onError += (rapidDownloder_onError);
rapidDownloder.onProgressChanged += (rapidDownloder_onProgressChanged);
rapidDownloder.onAllCompleted += (rapidDownloder_onAllCompleted);
rapidDownloder.SkipOnError = checkBox1.Checked;
var Links = richTextBox1.Text.Split('\n');
foreach (var link in Links)
{
if (string.IsNullOrEmpty(link.Trim())) continue;
rapidDownloder.Links.Add(link);
}
rapidDownloder.StartAll();
فقط كافيه واسه رويدادشو متدهارو تعريف كنين تا كاري كه ميخواين واستون انجام بده