Simple Rapidshare Download Class C#






4.09/5 (15 votes)
By using this class, you can simply download multiple rapidshare links at once! (parallel)
Introduction
By Using Rapidshare Downloader class, you can easily Download Multiple Files at the same time (Parallel) and also control every step of the process.
Specifications
- Support & Control User Authentication
- Search for Authenticated Cookies
- Create Credentials Base on User Accounts
- Event Base Download Class
onChanged
onError
onComplete
onAllComplete
onProgressChanged
- Status & Progress Report for each Thread at each Step
- Supports Safe Download Cancellation
- Supports ASP.NET
- Supports other Services like (Megaupload, Hotfile,...)
Background
One of the reasons which led me to write this article is that in some cases you need to use HttpWebRequest
to authorize users to the services like Rapidshare.com before downloading files. In these cases, if you try .NET Network Credential, you can see that the Authorization HTTP header is not generated, so you cannot authorize your users.
So I write this article to show you how you can download secure files using C#.
Class Diagram
Using the Code
The source which is provided for this article is the sample usage of the downloader class in Windows Form Environment. You can also use this class in ASP.NET by Enabling "Async
" on the Pages.
<%@ Page Language="C#" AutoEventWireup="true" Async="true"
private QDownloadParam QDownload(QDownloadParam param)
{
//Create the HttpWebRequest Object
param.Status = "Connecting... (" + param.Link + ")";
param.Worker.ReportProgress(1, param);
var URL = new Uri(param.Link.Trim());
var req = (HttpWebRequest)WebRequest.Create(URL);
//Allow Auto Redirections, because after Authentications,
//links are going to be changed.
req.AllowAutoRedirect = true;
//check if the user set the Credentials or not
if (!string.IsNullOrEmpty(param.Username))
{
//Assigning Basic Authorization HTTP Header to HttpWebRequest
byte[] authBytes = Encoding.UTF8.GetBytes
((param.Username + ":" + param.Password).ToCharArray());
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);
}
req.MaximumAutomaticRedirections = 4;
//User Agent Set as Firefox
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
//Accept any kind of files!
req.Accept = "*/*";
req.KeepAlive = true;
req.Timeout = 9999999; //prefRequestTimeout
//Search for the Authentication cookies
req.CookieContainer = GetUriCookieContainer(URL.AbsoluteUri);
// Get the stream from the returned web response
HttpWebResponse webresponse = null;
try
{
webresponse = (HttpWebResponse)req.GetResponse();
//Check if the Response Redirect occurred or not
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
{
//Get the File and write it to path
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;//Set the buffer Length
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;
}
Fields
FileDirectory
: Exact path for the folder which downloaded files save to itUserName
: Your Account-ID (Username)Password
: Your Account PasswordLinks
: List of the Rapidshare Links which you want to be downloadedJobs
: Contains all the download Job objectsOnlineJobs
: Contains the number of current downloads job which are running
Methods
void StartAll()
: Start to download all the links in Link list in Parallel Modeint CancelAll()
: Cancel all the downloads
Events
onChanged
: Send the current status of each download job when it is changedonError
: Send each error message with detailsoncompleted
: Raise when each download job is finishedonAllCompleted
: Raise when all download jobs are finishedonProgressChanged
: Send each download progress percentage when it changes
Points of Interest
One of the interesting points of this project is that you can use both upload and download ability to build a file service which can work on different servers and services like Rapidshare, Megaupload, Windows Live Storage,...
History
Version 1.0