SQNco Developers Imagination power is my innovative engine!

29Jul/093

Simple Rapidshare Download Class C#

QrapiDownloadr

Download QRapidshareDownload.zip (100kb) SOURCE & DEMO

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 reason which lead 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, so in this 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 by using C#

Class Diagram

class

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.

1
<%@ Page Language="C#" AutoEventWireup="true" Async="true" ...
?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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);
         //  Alow Auto Redirections, because after Authentications, links 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 &gt; 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: this is the List of the Rapidshare Links which you wants to be downloaded.
  • Jobs: Contains all the Downloads Job objects.
  • OnlineJobs: Contains the number of current Downloads Job which is 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 its changed.
  • onError: send each error messages with details.
  • oncompleted: raise when each download job is finish.
  • onAllCompleted: raise when All downloads job are finished.
  • onProgressChanged: send each download Progress Percentage when its change.

Points of Interest

One of the interesting point of this project is that you can use both upload and download ability to build a file service which can works on different servers and services like Rapidshare, Megaupload, windows Live Storage,...

History

Version 1.0

Related Project

Simple Upload File to Rapidshare Account Method using C#  Codeproject

License

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

Ghasem Heyrani-Nobari

Comments (3) Trackbacks (0)
  1. Hi,

    I’m wondering why the built-in Credentials feature doesn’t work on Rapidshare.

    CredentialCache cc = new CredentialCache();
    cc.Add(uri, “Basic”, new NetworkCredential(username, password));
    request.Credentials = cc;

    Any ideas?

  2. I do some research! but i couldn’t find anything!

  3. First of all. Thanks very much for your useful post.

    I just came across your blog and wanted to drop you a note telling you how impressed I was with the

    information you have posted here.

    Please let me introduce you some info related to this post and I hope that it is useful for community.

    There is a good C# resource site, Have alook

    http://CSharpTalk.com

    Thanks again
    Rahul


Leave a comment


No trackbacks yet.