Click here to Skip to main content
Click here to Skip to main content

Simple Upload File to Rapidshare Account Method using C#

By , 2 Apr 2009
 

Introduction

By using this class, you can easily upload your files to Rapidshare.com.

With RapidShare, you can send big files easily and in a secure manner.

This class supports the following type of Rapidshare accounts:

  • Premium accounts (type = 1)
  • Collector's accounts (type = 2)
  • Free users (type = 0)

After Selecting the file and uploading, you should see two links in the result Panel, one for downloading and one for deleting the file from Rapidshare.com.

Using the Code

You can see the full usage of this class in the source of the demo application.

For this application, I'm using Rapidshare version 1 API (the original API is made by Perl).

class QRapidshare
    {
        public string QUploadToRapidshare(string FilePath, string username,
            string password, int AccountType)
        {
            FileSystemInfo _file = new FileInfo(FilePath);
            DateTime dateTime2 = DateTime.Now;
            long l2 = dateTime2.Ticks;
            string s1 = "----------" + l2.ToString("x");
            System.Net.HttpWebRequest httpWebRequest = GetWebrequest(s1);
            using (System.IO.FileStream fileStream = new FileStream(_file.FullName,
                FileMode.Open, FileAccess.Read, FileShare.Read))
            {//Set Headers for Uploading
                byte[] bArr1 = Encoding.ASCII.GetBytes("\r\n--" + s1 + "\r\n");
                string s2 = GetRequestMessage(s1, _file.Name, username, password,
                    AccountType);
                byte[] bArr2 = Encoding.UTF8.GetBytes(s2);
                Stream memStream = new MemoryStream();
                memStream.Write(bArr1, 0, bArr1.Length);
                memStream.Write(bArr2, 0, bArr2.Length);
                byte[] buffer = new byte[1024];
                int bytesRead = 0;//Read File into memStream.
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);

                }
                httpWebRequest.ContentLength = memStream.Length;
                fileStream.Close();

                Stream requestStream = httpWebRequest.GetRequestStream();
//Send File from memStream to Rapidshare.com
                memStream.Position = 0;
                byte[] tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();
            }
            string tm = "";
            using (Stream stream = httpWebRequest.GetResponse().GetResponseStream())
            using (StreamReader streamReader = new StreamReader(stream))
            {
                tm = streamReader.ReadToEnd();

            }//Get Response from Rapidshare and Return the Links.
            return tm;
        }

        private string GetRequestMessage(string boundary, string FName,
            string username, string password, int AccountType)
        {
//Generate Headers exactly Like Rapidshare API v.1.0
            System.Text.StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("--");
            stringBuilder.Append(boundary);
            stringBuilder.Append("\r\n");
            stringBuilder.Append("Content-Disposition: form-data; name=\"toolmode2\"");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("1");
            stringBuilder.Append("\r\n");
            stringBuilder.Append(boundary);
            stringBuilder.Append("\r\n");
            if (AccountType != 0)//Free User
            {
                if (AccountType == 1) //Premium Account
                {
                    stringBuilder.Append(
                        "Content-Disposition: form-data; name=\"login\"");
                }
                else //Collector Account
                {
                    stringBuilder.Append(
                        "Content-Disposition: form-data; name=\"freeaccountid\"");
                }
                stringBuilder.Append("\r\n");
                stringBuilder.Append("\r\n");
                stringBuilder.Append(username);
                stringBuilder.Append("\r\n");
                stringBuilder.Append(boundary);
                stringBuilder.Append("\r\n");
                stringBuilder.Append
		("Content-Disposition: form-data; name=\"password\"");
                stringBuilder.Append("\r\n");
                stringBuilder.Append("\r\n");
                stringBuilder.Append(password);
                stringBuilder.Append("\r\n");
            }//else if Free User
//File Name
            stringBuilder.Append(boundary);
            stringBuilder.Append("\r\n");
            stringBuilder.Append("Content-Disposition: form-data; name=\"");
            stringBuilder.Append("filecontent");
            stringBuilder.Append("\"; filename=\"");
            stringBuilder.Append(FName);
            stringBuilder.Append("\"");
            stringBuilder.Append("\r\n");
//File Type
            stringBuilder.Append("Content-Type: ");
            stringBuilder.Append("multipart/form-data");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("Content-Transfer-Encoding: ");
            stringBuilder.Append("binary");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("\r\n");
            return stringBuilder.ToString();
        }

        private CookieContainer _cockies = new CookieContainer();
        private HttpWebRequest GetWebrequest(string boundary)
        {//Prepare for Uploading 
            WebClient wc = new WebClient();
            Uri url0 = new Uri( 
                "http://rapidshare.com/cgi-bin/rsapi.cgi?sub=nextuploadserver_v1");
            int uploadserver = int.Parse(wc.DownloadString(url0).Trim());
            //Find Free Upload Slot on Rapidshare servers.
            System.Uri uri = new Uri("http://rs" + uploadserver + "l3" +
                ".rapidshare.com/cgi-bin/upload.cgi");
            System.Net.HttpWebRequest httpWebRequest = (
                System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
            httpWebRequest.CookieContainer = _cockies;//Set Cookies for rapidshare
            httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            //Set Fake userAgent exactly like Rapidshare Manager
            httpWebRequest.UserAgent = "RapidUploader[v1,2]";
            //Set Fake Referer
            httpWebRequest.Referer = "http://rapidshare.com/";
            httpWebRequest.Method = "POST";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Timeout = -1;
            httpWebRequest.Headers.Add
		("Accept-Charset", "iSO-8859-1,utf-8;q=0.7,*;q=0.7");
            httpWebRequest.Headers.Add("Accept-Encoding", "identity");
            httpWebRequest.Headers.Add("Accept-Language", "de-de;q=0.5,en;q=0.3");
            return httpWebRequest;
        }
    }
//You can use this class in .NET Web, Window, WebService,...

In the next version, I want to add an Upload Speed Control and Progress Bar.

You can upload up to 2000 MB file to your Premium account, and up to 200 MB for Collectors account and Free users.

Points of Interest

You can also use this method for your web applications and dynamically upload your files to your Rapidshare.com account.

History

  • 2nd April, 2009: Version 1.0

License

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

About the Author

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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionUpdated the codememberMember 80246504 Oct '12 - 7:24 
Hello,
 
Thank you for providing such a great help, I modified the code to work with new API but due to some minor problem it is not working.
 
Can you please help me in this?
 
Thanks,
Nehali
AnswerRe: Updated the codememberRKillaars25 Mar '13 - 6:00 
Hi Nehali,
 
I am already trying for some days to write .NET code to upload a file to Rapidshare. Keep on getting the message that the subroutine is incorrect. Where you able to fix the minor bug? If yes": Would you mind to share the updated code to me?
 
Thank you in advance,
 
Ron
 
My Code:
 
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
 
        Dim strNextServerURL As String = "http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=nextuploadserver"
        Dim req As WebRequest = WebRequest.Create(strNextServerURL)
        Dim response = req.GetResponse().GetResponseStream()
        Dim reader As New StreamReader(response)
        Dim nextfreeserver = reader.ReadToEnd()
        req = Nothing
        response = Nothing
        reader = Nothing
 
        Dim method As String = "upload"
        Dim login As String = "#######"
        Dim password As String = "#######"
        Dim filename As String = "test12345.txt"
        Dim uploadurl As String = "https://rs" & nextfreeserver & ".rapidshare.com/cgi-bin/rsapi.cgi"
        Dim filepath = "C:\Users\Public\Documents\" & filename
        Dim uploadid As String = "11111111"
 
        Dim nvc As NameValueCollection = New NameValueCollection()
 
        nvc.Add("sub", method)
        nvc.Add("login", login)
        nvc.Add("password", password)
        nvc.Add("filename", "text12345.txt")
        'nvc.Add("uploadid", uploadid)
        Dim resp As String = ""
        resp = HttpUploadFile(uploadurl, filepath, "filecontent", "text/xml", nvc)
        MsgBox(resp)
    End Sub
 
Public Shared Function HttpUploadFile(url As String, file As String, paramName As String, contentType As String, nvc As NameValueCollection) As String
 
        Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
        Dim boundarybytes As Byte() = System.Text.Encoding.ASCII.GetBytes(vbCr & vbLf & "--" & boundary & vbCr & vbLf)
 
        Dim wr As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
        wr.ContentType = "multipart/form-data; boundary=" & boundary
        wr.Method = "POST"
        wr.KeepAlive = False
        wr.Timeout = 9999999
        wr.ProtocolVersion = HttpVersion.Version10
        Dim useragent As String = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"
        wr.UserAgent = useragent
 
        Dim rs As Stream = wr.GetRequestStream()
 
        Dim formdataTemplate As String = "Content-Disposition: form-data; name=""{0}""" & vbCr & vbLf & vbCr & vbLf & "{1}"
        For Each key As String In nvc.Keys
            rs.Write(boundarybytes, 0, boundarybytes.Length)
            Dim formitem As String = String.Format(formdataTemplate, key, nvc(key))
            Dim formitembytes As Byte() = System.Text.Encoding.UTF8.GetBytes(formitem)
            rs.Write(formitembytes, 0, formitembytes.Length)
        Next
        rs.Write(boundarybytes, 0, boundarybytes.Length)
 
        Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""" & vbCr & vbLf & "Content-Type: {2}" & vbCr & vbLf & vbCr & vbLf
        Dim header As String = String.Format(headerTemplate, paramName, file, contentType)
        Dim headerbytes As Byte() = System.Text.Encoding.UTF8.GetBytes(header)
        rs.Write(headerbytes, 0, headerbytes.Length)
 
        Dim fileStream As New FileStream(file, FileMode.Open, FileAccess.Read)
        Dim buffer As Byte() = New Byte(1024) {}
        Dim bytesRead As Integer = 0
        While (InlineAssignHelper(bytesRead, fileStream.Read(buffer, 0, buffer.Length))) <> 0
            rs.Write(buffer, 0, bytesRead)
        End While
        fileStream.Close()
 
        Dim trailer As Byte() = System.Text.Encoding.ASCII.GetBytes(vbCr & vbLf & "--" & boundary & "--" & vbCr & vbLf)
        rs.Write(trailer, 0, trailer.Length)
        rs.Close()
 
        Dim wresp As WebResponse = Nothing
        Try
            wresp = wr.GetResponse()
 
            Dim stream2 As Stream = wresp.GetResponseStream()
            Dim reader2 As New StreamReader(stream2)
            Return reader2.ReadToEnd()
 

            If wresp IsNot Nothing Then
                wresp.Close()
                wresp = Nothing
            End If
        Finally
            wr = Nothing
        End Try
    End Function
    Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
        target = value
        Return value
    End Function
 

QuestionDoesn't work for mememberMr.Extremer30 Mar '11 - 23:39 
Why always return savedfiles=0 forbiddenfiles=0 premiumaccount=0?
I have free user account. But i can't upload any files; actually file is sned to server but response of rapidshare isn't what i want. (download link of uploaded file)
AnswerRe: Doesn't work for mememberGhasem Heyrani Nobari30 Mar '11 - 23:53 
Actually I wrote this article, two years ago! and lot's of thing are changing from rapidshare.com side!
and the main idea behind this article is to show, how we can upload to 3rd party websites with different method of authentication and security.
 
So if you have time, you can debug my program to find out, what is going wrong, and post it here, so others can use it.
 
Regards.
 
QHN_PROF*AT*Yahoo.com
GeneralRe: Doesn't work for mememberMr.Extremer31 Mar '11 - 0:11 
Hm..., RapidShare provided Perl script for developers to perform such things at http://images.rapidshare.com/software/rsapiresume.pl; but actually i know nothing about of Perl. Can u help to translate script to C#?
GeneralRe: Doesn't work for mememberShoaibRiaz13 Apr '11 - 19:02 
Respected Sir, i got that lot of things have been changed on rapidshare, but please try make it better now again and make your this uploader application more efficient. it was really awesome and brilliant work and saved a lot of time of browsing. So please change it again and make it perfect and workable. Now this application is not working (uploading files)
when we want to upload file, it gives message after a few moments, "savedfiles=0 forbiddenfiles=0 premiumaccount=0"
so please look forward to it.
GeneralThx for your nice code , but premium doesn't work anymorememberSiedlerchr15 Aug '10 - 8:37 
Hey, first thx a lot for your code. It is very helpful, but it doesn't work anylonger for premium user.
As result you get savedfiles=0, forbiddenfiles=0.
 
It would be nice if you can update your code Smile | :)
GeneralRe: Thx for your nice code , but premium doesn't work anymoremembervsisman30 Aug '10 - 4:48 
it's working with premium accounts. check your code..
GeneralUpload more than 200mbmemberJose Carlos Ribeiro3 Feb '10 - 0:06 
Hello,
I'm using a premium account, but I can't upload more than 200MB.
Any ideas?
 
Thanks
Generalanother questionmemberejtixo16 Dec '09 - 11:58 
how is created stringbuilder? can i created it without contacting hosts?where i can read data to creating stringbuilder? i cant understand context Frown | :( thx so much
Generalmy questionmemberejtixo14 Dec '09 - 4:56 
please, can it be used for another server? or what is custom only for rapidshare.com? what i need to know for another server? thnx Smile | :)
GeneralRe: my questionmemberdavidgiga15 Dec '09 - 3:13 
It's only for Rapidshrare
If you want to use it with another Hoster you need to know their API and how you can send the data to them
GeneralRe: my question [modified]memberejtixo15 Dec '09 - 18:17 
how i can find their api?... can it be readed in source page or i must contact him? Sniff | :^) and are important fake informations?
 
modified on Wednesday, December 16, 2009 5:52 AM

GeneralMy vote of 2memberdavidgiga11 Dec '09 - 1:04 
too much code, no status output, uses not the RS API as it should
NewsNew RS-Uploader Class [modified]memberdavidgiga11 Dec '09 - 1:01 
I just wanted to say that I will post my new RS Uplaoder Class today.
It supports a % and kb/s output and it is muss less code than this one.
 
I will post the link here later.
 
PS: the class even doesn't use that much RAM (only about 5MB with the programm)
 
C# Rapidshare Uploader Class[^]
 
modified on Friday, December 11, 2009 1:47 PM

Generalawsome codingmemberAndy329 Oct '09 - 2:41 
This I find very usefull coding - many thanks mate Wink | ;)
 
Making any progress with the upload progress and speed ? Those 2 additions would makes this a much better application than the one rapidshare is providing (encountered so many bugs with the rs uploader from rapidshare that I stopped counting) - hopefully you find the time to complete these 2 additions, but in any case, I'm grateful for the class as is, works excellent !
GeneralRe: awsome codingmemberMichalss12 Oct '09 - 8:47 
Yeah progress bar would be great. Please ?
GeneralMy requestmemberSoftsiva31 Aug '09 - 22:10 
I wanna create rapidshare downloader for premium users.... How to get the premium link from rapidshare?
 
Thanks and regards,
Softsivachand

GeneralRe: My requestmemberkojoo8931 Aug '09 - 22:13 
Simple Rapidshare Download Class C# [^]
General.zip Files don't work after UploadmemberBjoern M.20 Jul '09 - 12:02 
I uploaded a few Zip-Files for testing.
But when I download the Files again, they are broken. WinRar can not unrar them.
GeneralRe: .zip Files don't work after UploadmemberVitali Kaspler25 Jul '09 - 1:40 
For some reason, 2 last bytes of the uploaded file are cuted. Thats why the RAR archive is broken.
So I just added 2 additional bytes to the requestStream... They are cuted and the original file stays OK ...
 
Here are the changes:
 
QUploadToRapidshare.cs:
Line 33:        httpWebRequest.ContentLength = memStream.Length + 2; // add 2 bytes

Line 42:        requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                byte[] addTwoBytes = new byte[2];
                addTwoBytes[0] = 0;
                addTwoBytes[1] = 0;
                requestStream.Write(addTwoBytes, 0, addTwoBytes.Length);
                requestStream.Close();
 
Good luck! Smile | :)
GeneralRe: .zip Files don't work after UploadmemberBjoern M.25 Jul '09 - 3:05 
Works fine!
Thanks

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 2 Apr 2009
Article Copyright 2009 by Ghasem Heyrani Nobari
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid