Click here to Skip to main content
Click here to Skip to main content
Go to top

Simple Rapidshare Download Class C#

, 29 Jul 2009
Rate this:
Please Sign up or sign in to vote.
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 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)

Share

About the Author

Ghasem Heyrani Nobari
Software Developer (Senior)
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Ghasem - Heyrani-Nobari
Qasem*AT*SQNco.com

Comments and Discussions

 
Questionnot working? Pinmemberklabauter198723-Aug-09 4:44 
I tried it, and it seems that i can't download.
I Always get message "Check Username/Password"
But its 100% correct.
AnswerRe: not working? Pinmemberklabauter198723-Aug-09 4:55 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 29 Jul 2009
Article Copyright 2009 by Ghasem Heyrani Nobari
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid