Click here to Skip to main content
6,629,885 members and growing! (21,345 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

Send a content type “multipart/form-data” request from C#

By Pablo Russoniello

Send a content type “multipart/form-data” request from C#
C# 1.0, C# 2.0, Windows, .NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0VS.NET2003, VS2005, Dev
Posted:1 Feb 2007
Updated:5 Mar 2007
Views:49,047
Bookmarked:16 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
6 votes for this article.
Popularity: 1.75 Rating: 2.25 out of 5
2 votes, 33.3%
1
1 vote, 16.7%
2
2 votes, 33.3%
3
1 vote, 16.7%
4

5

Introduction

Here we will describe a simple procedure to make a request of type "multipart/form-data" from C# using the HttpWebRequest class. Taking as refence the article published in the web : Browsing_the_WEB_with_C_.asp .

Content

The big problem of this type of request is how to prepare the data package that will be passed to the class. For this, the more easy way to do this is making a string with the data in text form. You will must be careful with this, because if you put wrong a character or separator the package wont get to destiny successfully.

The next method make this action about a parameters collection, these parameters can be different type, because by this way you will can sending the file content.

"cs">private string GetPostData() 
{ 
    string boundary = "--" + this._Boundary; 
    int arrReqs = this._ParamsCollection.Count * 5; 
    string[] auxReqBody = new string[arrReqs]; 
    int count = 0; 
    foreach(ParamsStruct par in this._ParamsCollection) 
    { 
        auxReqBody[count] = boundary; 
        count++; 
        switch (par.Type) 
        { 
            case ParamsStruct.ParamType.File: 
            { 
                auxReqBody[count] = "Content-Disposition: file; name=\"" + par.Name + "\"; filename=\"" + par.GetOnlyFileName() + "\""; 
                count++; 
                auxReqBody[count] = "Content-Type: text/plain"; 
                count++; 
                auxReqBody[count] = ""; 
                count++; 
                auxReqBody[count] = par.StringValue; 
                count++; 
                break; 
            } 
            case ParamsStruct.ParamType.Parameter: 
            default: 
            { 
                auxReqBody[count] = "Content-Disposition: form-data; name=\"" + par.Name + "\""; 
                count++; 
                auxReqBody[count] = ""; 
                count++; 
                auxReqBody[count] = par.StringValue; 
                count++; 
                break; 
            } 
        } 
    } 
    auxReqBody[count] = boundary; 
    count++; 
    string requestBody = String.Join("\r\n",auxReqBody); 
    return requestBody;
} 

Then if we inform in the parameters collection : one parameter of type "Parameter", name "param1" and value "param1Value" and one parameter of type "File", name "file", file name "fileName1.txt" and value "Content of fileName1.txt", after run of this method you will obtain a text with this format:

--AaB03x\r\n
Content-Disposition: form-data; name="param1"\r\n
\r\n
param1Value\r\n
--AaB03x\r\n
Content-Disposition: file; name="file"; filename="fileName1.txt"\r\n
Content-Type: text/plain\r\n
\r\n
Content of fileName1.txt \r\n
--AaB03x\r\n

After this, we will use a method similar to this one, for sending the information to the required page.

"cs">public void PostData ()
{ 
    //Set URL 

    Uri urlUri = new Uri(_URL); 
    //Encoding postData 

    ASCIIEncoding encoding = new ASCIIEncoding(); 
    string postData = this.GetPostData(); 
    byte[] buffer = encoding.GetBytes( postData ); 
    // Prepare web request... 

    HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create(urlUri); 
    // We use POST ( we can also use GET ) 

    myRequest.Method = this._Method; 
    myRequest.AllowWriteStreamBuffering = true; 
    // Set the content type to a FORM 

    string auxContent = this._ContentType; 
    if (this._Boundary.Length > 0) 
        auxContent += "boundary=" + this._Boundary; 
    myRequest.ContentType = auxContent; 
    // Get length of content 

    myRequest.Accept = this._Accept; 
    myRequest.ContentLength = buffer.Length; 
    // Get request stream 

    Stream newStream = myRequest.GetRequestStream(); 
    // Send the data. 

    newStream.Write(buffer,0,buffer.Length); 
    // Close stream 

    newStream.Close(); 
    _myHttpWebResponse= (HttpWebResponse)myRequest.GetResponse(); 
    // Set the response to ResponseStream property 

    this._ResponseStream = _myHttpWebResponse.GetResponseStream();
} 

For finishing this, we must process the request stream returned by the required page. In this case I declare one property inside class that transform the response stream to string.

"cs">public string ResponseString
{ 
    get 
    { 
        string resultData = ""; 
        StreamReader streamRead = new StreamReader( _ResponseStream ); 
        Char[] readBuffer = new Char[256]; 
        // Read from buffer 

        int count = streamRead.Read( readBuffer, 0, 256 ); 
        while (count > 0) 
        { 
            // get string 

            resultData += new String( readBuffer, 0, count); 
            // Write the data 

            Console.WriteLine( resultData ); 
            // Read from buffer 

            count = streamRead.Read( readBuffer, 0, 256); 
        } 
        // Release the response object resources. 

        streamRead.Close(); 
        return resultData; 
    }
} 

In simple way, this will adapt to another content type. Remember that the key is the form for load the data package.

For SSL page type see request_SSL_from_C_.asp

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Pablo Russoniello


Member

Occupation: Web Developer
Location: Argentina Argentina

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 17 of 17 (Total in Forum: 17) (Refresh)FirstPrevNext
GeneralSending Multiple image PinmemberMember 474402917:09 1 Apr '09  
General{"The operation has timed out"} PinmemberMichael Sync5:41 27 Aug '08  
Questionbinary data Pinmemberp. tj13:51 16 Apr '07  
AnswerRe: binary data Pinmemberstibstibstib1:26 7 Jun '07  
GeneralRe: binary data Pinmemberstibstibstib4:01 7 Jun '07  
QuestionRe: binary data(but how to code) Pinmemberwinart18:18 22 Jul '07  
GeneralAny difference to post file to JSP page Pinmembervdonthi9:26 6 Apr '07  
AnswerRe: Any difference to post file to JSP page PinmemberPablo Russoniello5:54 9 Apr '07  
Generalopen the POST request in a browser PinmemberZilberbal20:40 4 Mar '07  
AnswerRe: open the POST request in a browser PinmemberPablo Russoniello2:40 5 Mar '07  
GeneralRe: open the POST request in a browser PinmemberZilberbal1:17 8 Mar '07  
Generalhow to read xml data from a http post Pinmemberdeepa l13:16 22 Feb '07  
AnswerRe: how to read xml data from a http post PinmemberPablo Russoniello2:53 23 Feb '07  
Generalread xml data from a http post Pinmember13:13 22 Feb '07  
QuestionTried to use your class Pinmemberalpha_krone22:13 21 Feb '07  
AnswerRe: Tried to use your class PinmemberPablo Russoniello2:31 22 Feb '07  
GeneralRe: Tried to use your class Pinmemberalpha_krone16:04 22 Feb '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 5 Mar 2007
Editor:
Copyright 2007 by Pablo Russoniello
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project