Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#

Simple Rapidshare Download Class C#

Rate me:
Please Sign up or sign in to vote.
4.09/5 (15 votes)
29 Jul 2009GPL32 min read 63.3K   1.5K   55   16
By using this class, you can simply download multiple rapidshare links at once! (parallel)
Image 1

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

Image 2

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.

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" Async="true"  
C#
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 it
  • UserName: Your Account-ID (Username)
  • Password: Your Account Password
  • Links: List of the Rapidshare Links which you want to be downloaded
  • Jobs: Contains all the download Job objects
  • OnlineJobs: Contains the number of current downloads job which are running

Methods

  • void StartAll(): Start to download all the links in Link list in Parallel Mode
  • int CancelAll(): Cancel all the downloads

Events

  • onChanged: Send the current status of each download job when it is changed
  • onError: Send each error message with details
  • oncompleted: Raise when each download job is finished
  • onAllCompleted: Raise when all download jobs are finished
  • onProgressChanged: 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 

Related Project

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Team Leader
Iran (Islamic Republic of) Iran (Islamic Republic of)
Ghasem - Nobari
Qasem*AT*SQNco.com

Comments and Discussions

 
Questionthank you nice class Pin
Member 107103418-Apr-15 13:10
Member 107103418-Apr-15 13:10 
Question! Pin
alejandro29A20-Jun-11 14:32
alejandro29A20-Jun-11 14:32 
AnswerRe: ! Pin
alejandro29A20-Jun-11 14:43
alejandro29A20-Jun-11 14:43 
Questionnot working? Pin
klabauter198723-Aug-09 4:44
klabauter198723-Aug-09 4:44 
AnswerRe: not working? Pin
klabauter198723-Aug-09 4:55
klabauter198723-Aug-09 4:55 
QuestionSimply not workin! Pin
RonaldoCR921-Aug-09 2:31
RonaldoCR921-Aug-09 2:31 
AnswerRe: Simply not workin! Pin
Ghasem Nobari22-Aug-09 5:45
Ghasem Nobari22-Aug-09 5:45 
GeneralRe: Simply not workin! Pin
RonaldoCR922-Aug-09 19:47
RonaldoCR922-Aug-09 19:47 
GeneralVery Useful! Pin
doung3029-Jul-09 23:03
doung3029-Jul-09 23:03 
Thanks Big Grin | :-D
Questionwhy?? Pin
Ashutosh Bhawasinka29-Jul-09 3:07
Ashutosh Bhawasinka29-Jul-09 3:07 
AnswerRe: why?? Pin
Ghasem Nobari29-Jul-09 3:19
Ghasem Nobari29-Jul-09 3:19 
QuestionHow to pause and resume Pin
jayaveer_b329-Jul-09 3:04
jayaveer_b329-Jul-09 3:04 
AnswerRe: How to pause and resume Pin
Ghasem Nobari29-Jul-09 3:16
Ghasem Nobari29-Jul-09 3:16 
GeneralMy vote of 2 Pin
Dave Kreskowiak29-Jul-09 1:47
mveDave Kreskowiak29-Jul-09 1:47 
GeneralRe: My vote of 2 Pin
Ghasem Nobari29-Jul-09 2:35
Ghasem Nobari29-Jul-09 2:35 
GeneralRe: My vote of 2 Pin
dvhh30-Jul-09 4:04
dvhh30-Jul-09 4:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.