locked
How to post data using C# HttpWebRequest class

    Question

  • hi

    I am working on an application that involves uploading images into Imageshack.us(an online image host).

    The problem is that they don't have any API's and i have to write my own, and to be honest i'm not very good at that.

     

    I have searched for a good solution online and found a piece of code that allows you to upload Images to a URl, using post.

    The problem with this code is that it can be used to post images and Imageshack.us requires an another parameter a developer key with parameter name as key to be in the posted data(please see the http://code.google.com/p/imageshackapi/wiki/ImageshackAPI)

    can anybody please modify the following code so that , i can add that parameter and post data

     

    long length = 0;
       string boundary = "----------------------------" +
       DateTime.Now.Ticks.ToString("x");
    
    
       HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
       httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
       httpWebRequest2.Method = "POST";
       httpWebRequest2.KeepAlive = true;
    
       Stream memStream = new System.IO.MemoryStream();
    
       byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
    
    
       memStream.Write(boundarybytes, 0, boundarybytes.Length);
       length += boundarybytes.Length;
    
       string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n Content-Type: image/gif\r\n\r\n";
    
       string header = string.Format(headerTemplate, "fileupload", filename);
    
       byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
    
       memStream.Write(headerbytes, 0, headerbytes.Length);
       length += headerbytes.Length;
    
       FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
       byte[] buffer = new byte[1024];
    
       int bytesRead = 0;
    
       while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
       {
        memStream.Write(buffer, 0, bytesRead);
        length += bytesRead;
       }
    
    
       memStream.Write(boundarybytes, 0, boundarybytes.Length);
       length += boundarybytes.Length;
    
       fileStream.Close();
    
       httpWebRequest2.ContentLength = memStream.Length;
       httpWebRequest2.
    
       Stream requestStream = httpWebRequest2.GetRequestStream();
    
       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();
    
    
       WebResponse webResponse2 = httpWebRequest2.GetResponse();
    
       Stream stream2 = webResponse2.GetResponseStream();
       StreamReader reader2 = new StreamReader(stream2);
    
    
       string resp = reader2.ReadToEnd();
    
       webResponse2.Close();
       httpWebRequest2 = null;
       webResponse2 = null;
       return resp;
    

    this is the sample form that i want to recreate in C#

    <form method="post" action="http://www.imageshack.us/upload_api.php" enctype="multipart/form-data">
    <input type="hidden" name="key" value="YOUR_API_KEY" /> 
    <input type="file" name="fileupload" id="fileupload"/>
    <input type="submit" value="Host It" /> </form>
    

     


    get C# code samples and tips at C# Programming help
    • Edited by vamsi_krishna Sunday, September 12, 2010 1:25 PM added more information
    Sunday, September 12, 2010 1:04 PM

Answers

  • The following code is what worked for me, hope it will solve your problems too.

     

    using System;
    using System.IO;
    using System.Web;
    using System.Net;
    using System.Text;
    using System.Drawing;
    using System.Xml.Serialization;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    
    namespace Imageshack
    {
      public class ImageshackAPI
      {
        public string Upload(string fileName)
        {
          try
          {
            string contentType = "image/jpeg"; ;
            CookieContainer cookie = new CookieContainer();
            NameValueCollection par = new NameValueCollection();
            par["MAX_FILE_SIZE"] = "3145728";
            par["refer"] = "";
            par["brand"] = "";
            par["key"] = "YOUR API Key";
            par["optimage"] = "1";
            par["rembar"] = "1";
            par["submit"] = "host it!";
            List<string> l = new List<string>();
            string resp;
            par["optsize"] = "resample";
            resp = UploadFileEx(fileName, "http://www.imageshack.us/upload_api.php", "fileupload", contentType, par, cookie);
            return resp;
          }
          catch (Exception ex)
          {
            return ex.Message;
          }
        }
    
        private string UploadFileEx(string uploadfile, string url, string fileFormName, string contenttype, NameValueCollection querystring, CookieContainer cookies)
        {
          if ((fileFormName == null) ||
            (fileFormName.Length == 0))
          {
            fileFormName = "fileupload";
          }
    
          if ((contenttype == null) ||
            (contenttype.Length == 0))
          {
            contenttype = "application/octet-stream";
          }
    
    
          string postdata;
          postdata = "?";
          if (querystring != null)
          {
            foreach (string key in querystring.Keys)
            {
              postdata += key + "=" + querystring.Get(key) + "&";
            }
          }
          Uri uri = new Uri(url + postdata);
    
    
          string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
          HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
          webrequest.CookieContainer = cookies;
          webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
          webrequest.Method = "POST";
    
    
          // Build up the post message header
          StringBuilder sb = new StringBuilder();
          sb.Append("--");
          sb.Append(boundary);
          sb.Append("\r\n");
          sb.Append("Content-Disposition: form-data; name=\"");
          sb.Append(fileFormName);
          sb.Append("\"; filename=\"");
          sb.Append(Path.GetFileName(uploadfile));
          sb.Append("\"");
          sb.Append("\r\n");
          sb.Append("Content-Type: ");
          sb.Append(contenttype);
          sb.Append("\r\n");
          sb.Append("\r\n");
    
          string postHeader = sb.ToString();
          byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
    
          // Build the trailing boundary string as a byte array
          // ensuring the boundary appears on a line by itself
          byte[] boundaryBytes =
              Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
    
          FileStream fileStream = new FileStream(uploadfile,
                        FileMode.Open, FileAccess.Read);
          long length = postHeaderBytes.Length + fileStream.Length +
                              boundaryBytes.Length;
          webrequest.ContentLength = length;
    
          Stream requestStream = webrequest.GetRequestStream();
    
          // Write out our post header
          requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
    
          // Write out the file contents
          byte[] buffer = new Byte[checked((uint)Math.Min(4096,
                       (int)fileStream.Length))];
          int bytesRead = 0;
          while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            requestStream.Write(buffer, 0, bytesRead);
    
          // Write out the trailing boundary
          requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
          WebResponse responce = webrequest.GetResponse();
          Stream s = responce.GetResponseStream();
          XmlSerializer xSerializer = new XmlSerializer(typeof(imginfo));
          imginfo ii = (imginfo)xSerializer.Deserialize(s);
          imginfoLinks ifl = ii.links;
          fileStream.Close();
          s.Close();
          return ifl.image_link;
          
    
        }
      }
    }
    

    the following is the XML deserialization class used in the above class

     

    using System.Xml.Serialization;
    
    namespace Imageshack
    {
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ns.imageshack.us/imginfo/7/", IsNullable = false)]
      public partial class imginfo
      {
    
        private imginfoRating ratingField;
    
        private imginfoFiles filesField;
    
        private imginfoResolution resolutionField;
    
        private string classField;
    
        private string visibilityField;
    
        private imginfoUploader uploaderField;
    
        private imginfoLinks linksField;
    
        private byte versionField;
    
        private uint timestampField;
    
        /// <remarks/>
        public imginfoRating rating
        {
          get
          {
            return this.ratingField;
          }
          set
          {
            this.ratingField = value;
          }
        }
    
        /// <remarks/>
        public imginfoFiles files
        {
          get
          {
            return this.filesField;
          }
          set
          {
            this.filesField = value;
          }
        }
    
        /// <remarks/>
        public imginfoResolution resolution
        {
          get
          {
            return this.resolutionField;
          }
          set
          {
            this.resolutionField = value;
          }
        }
    
        /// <remarks/>
        public string @class
        {
          get
          {
            return this.classField;
          }
          set
          {
            this.classField = value;
          }
        }
    
        /// <remarks/>
        public string visibility
        {
          get
          {
            return this.visibilityField;
          }
          set
          {
            this.visibilityField = value;
          }
        }
    
        /// <remarks/>
        public imginfoUploader uploader
        {
          get
          {
            return this.uploaderField;
          }
          set
          {
            this.uploaderField = value;
          }
        }
    
        /// <remarks/>
        public imginfoLinks links
        {
          get
          {
            return this.linksField;
          }
          set
          {
            this.linksField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public byte version
        {
          get
          {
            return this.versionField;
          }
          set
          {
            this.versionField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public uint timestamp
        {
          get
          {
            return this.timestampField;
          }
          set
          {
            this.timestampField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoRating
      {
    
        private byte ratingsField;
    
        private decimal avgField;
    
        /// <remarks/>
        public byte ratings
        {
          get
          {
            return this.ratingsField;
          }
          set
          {
            this.ratingsField = value;
          }
        }
    
        /// <remarks/>
        public decimal avg
        {
          get
          {
            return this.avgField;
          }
          set
          {
            this.avgField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoFiles
      {
    
        private imginfoFilesImage imageField;
    
        private imginfoFilesThumb thumbField;
    
        private ushort serverField;
    
        private ushort bucketField;
    
        /// <remarks/>
        public imginfoFilesImage image
        {
          get
          {
            return this.imageField;
          }
          set
          {
            this.imageField = value;
          }
        }
    
        /// <remarks/>
        public imginfoFilesThumb thumb
        {
          get
          {
            return this.thumbField;
          }
          set
          {
            this.thumbField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public ushort server
        {
          get
          {
            return this.serverField;
          }
          set
          {
            this.serverField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public ushort bucket
        {
          get
          {
            return this.bucketField;
          }
          set
          {
            this.bucketField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoFilesImage
      {
    
        private ushort sizeField;
    
        private string contenttypeField;
    
        private string valueField;
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public ushort size
        {
          get
          {
            return this.sizeField;
          }
          set
          {
            this.sizeField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute("content-type")]
        public string contenttype
        {
          get
          {
            return this.contenttypeField;
          }
          set
          {
            this.contenttypeField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlTextAttribute()]
        public string Value
        {
          get
          {
            return this.valueField;
          }
          set
          {
            this.valueField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoFilesThumb
      {
    
        private ushort sizeField;
    
        private string contenttypeField;
    
        private string valueField;
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public ushort size
        {
          get
          {
            return this.sizeField;
          }
          set
          {
            this.sizeField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute("content-type")]
        public string contenttype
        {
          get
          {
            return this.contenttypeField;
          }
          set
          {
            this.contenttypeField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlTextAttribute()]
        public string Value
        {
          get
          {
            return this.valueField;
          }
          set
          {
            this.valueField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoResolution
      {
    
        private ushort widthField;
    
        private ushort heightField;
    
        /// <remarks/>
        public ushort width
        {
          get
          {
            return this.widthField;
          }
          set
          {
            this.widthField = value;
          }
        }
    
        /// <remarks/>
        public ushort height
        {
          get
          {
            return this.heightField;
          }
          set
          {
            this.heightField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoUploader
      {
    
        private string ipField;
    
        /// <remarks/>
        public string ip
        {
          get
          {
            return this.ipField;
          }
          set
          {
            this.ipField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoLinks
      {
    
        private string image_linkField;
    
        private string image_htmlField;
    
        private string image_bbField;
    
        private string image_bb2Field;
    
        private string thumb_linkField;
    
        private string thumb_htmlField;
    
        private string thumb_bbField;
    
        private string thumb_bb2Field;
    
        private string yfrog_linkField;
    
        private string yfrog_thumbField;
    
        private string ad_linkField;
    
        private string done_pageField;
    
        /// <remarks/>
        public string image_link
        {
          get
          {
            return this.image_linkField;
          }
          set
          {
            this.image_linkField = value;
          }
        }
    
        /// <remarks/>
        public string image_html
        {
          get
          {
            return this.image_htmlField;
          }
          set
          {
            this.image_htmlField = value;
          }
        }
    
        /// <remarks/>
        public string image_bb
        {
          get
          {
            return this.image_bbField;
          }
          set
          {
            this.image_bbField = value;
          }
        }
    
        /// <remarks/>
        public string image_bb2
        {
          get
          {
            return this.image_bb2Field;
          }
          set
          {
            this.image_bb2Field = value;
          }
        }
    
        /// <remarks/>
        public string thumb_link
        {
          get
          {
            return this.thumb_linkField;
          }
          set
          {
            this.thumb_linkField = value;
          }
        }
    
        /// <remarks/>
        public string thumb_html
        {
          get
          {
            return this.thumb_htmlField;
          }
          set
          {
            this.thumb_htmlField = value;
          }
        }
    
        /// <remarks/>
        public string thumb_bb
        {
          get
          {
            return this.thumb_bbField;
          }
          set
          {
            this.thumb_bbField = value;
          }
        }
    
        /// <remarks/>
        public string thumb_bb2
        {
          get
          {
            return this.thumb_bb2Field;
          }
          set
          {
            this.thumb_bb2Field = value;
          }
        }
    
        /// <remarks/>
        public string yfrog_link
        {
          get
          {
            return this.yfrog_linkField;
          }
          set
          {
            this.yfrog_linkField = value;
          }
        }
    
        /// <remarks/>
        public string yfrog_thumb
        {
          get
          {
            return this.yfrog_thumbField;
          }
          set
          {
            this.yfrog_thumbField = value;
          }
        }
    
        /// <remarks/>
        public string ad_link
        {
          get
          {
            return this.ad_linkField;
          }
          set
          {
            this.ad_linkField = value;
          }
        }
    
        /// <remarks/>
        public string done_page
        {
          get
          {
            return this.done_pageField;
          }
          set
          {
            this.done_pageField = value;
          }
        }
      }
    }
    


    get C# code samples and tips at C# Programming help
    • Marked as answer by vamsi_krishna Monday, September 27, 2010 6:18 AM
    Monday, September 27, 2010 6:18 AM

All replies

  • They do have an API http://imageshack.us/content.php?page=developer , you just need to request a key so that you can utilize it.

     

     

     

     

    • Marked as answer by Bin-ze Zhao Thursday, September 16, 2010 9:56 AM
    • Unmarked as answer by vamsi_krishna Monday, September 27, 2010 6:18 AM
    Sunday, September 12, 2010 4:25 PM
  • Hi, Vamsi_Krishna,

    I'm not aware of the specific image hosting provider, but still you want to upload the image through your code,

    Simply use the WebClient Class in the System.Net namespace

     public void imageUpload()
        {
          WebClient wc = new WebClient();
    
          NetworkCredential cred = new NetworkCredential("username", "password");
    
          wc.Credentials = cred;
    
          wc.UploadFile("path where you want to upload", "POST", "full qualified file path");
          
        }
    

     


    Regards Thurupathan My blog : http://thurupathan.spaces.live.com
    • Proposed as answer by thuruv Sunday, September 12, 2010 4:40 PM
    • Unproposed as answer by vamsi_krishna Sunday, September 12, 2010 4:48 PM
    Sunday, September 12, 2010 4:40 PM
  • No they don't have an API.

    Please check once again

    I have a developer key, if you visit there libraries page the above form is what you see


    get C# code samples and tips at C# Programming help
    Sunday, September 12, 2010 4:44 PM
  • This does not work for my problem

    Anyways thank you


    get C# code samples and tips at C# Programming help
    Sunday, September 12, 2010 4:49 PM
  • Hi,

    You should try Kirk's advise first, as the website has clearly stated out:

    The ImageShack Developer center allows a complete integration of ImageShack's services into any website or software via the use of our XML API, is subject to the ImageShack Terms of Service, and is free to use.

    If this doesn't work, you can contact ImageShack to consult this, we are here obviously can't help you out with this since they might have certain rules on how you will post the data they required.

    Thanks

    Binze


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Thursday, September 16, 2010 10:00 AM
  • The following code is what worked for me, hope it will solve your problems too.

     

    using System;
    using System.IO;
    using System.Web;
    using System.Net;
    using System.Text;
    using System.Drawing;
    using System.Xml.Serialization;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    
    namespace Imageshack
    {
      public class ImageshackAPI
      {
        public string Upload(string fileName)
        {
          try
          {
            string contentType = "image/jpeg"; ;
            CookieContainer cookie = new CookieContainer();
            NameValueCollection par = new NameValueCollection();
            par["MAX_FILE_SIZE"] = "3145728";
            par["refer"] = "";
            par["brand"] = "";
            par["key"] = "YOUR API Key";
            par["optimage"] = "1";
            par["rembar"] = "1";
            par["submit"] = "host it!";
            List<string> l = new List<string>();
            string resp;
            par["optsize"] = "resample";
            resp = UploadFileEx(fileName, "http://www.imageshack.us/upload_api.php", "fileupload", contentType, par, cookie);
            return resp;
          }
          catch (Exception ex)
          {
            return ex.Message;
          }
        }
    
        private string UploadFileEx(string uploadfile, string url, string fileFormName, string contenttype, NameValueCollection querystring, CookieContainer cookies)
        {
          if ((fileFormName == null) ||
            (fileFormName.Length == 0))
          {
            fileFormName = "fileupload";
          }
    
          if ((contenttype == null) ||
            (contenttype.Length == 0))
          {
            contenttype = "application/octet-stream";
          }
    
    
          string postdata;
          postdata = "?";
          if (querystring != null)
          {
            foreach (string key in querystring.Keys)
            {
              postdata += key + "=" + querystring.Get(key) + "&";
            }
          }
          Uri uri = new Uri(url + postdata);
    
    
          string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
          HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
          webrequest.CookieContainer = cookies;
          webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
          webrequest.Method = "POST";
    
    
          // Build up the post message header
          StringBuilder sb = new StringBuilder();
          sb.Append("--");
          sb.Append(boundary);
          sb.Append("\r\n");
          sb.Append("Content-Disposition: form-data; name=\"");
          sb.Append(fileFormName);
          sb.Append("\"; filename=\"");
          sb.Append(Path.GetFileName(uploadfile));
          sb.Append("\"");
          sb.Append("\r\n");
          sb.Append("Content-Type: ");
          sb.Append(contenttype);
          sb.Append("\r\n");
          sb.Append("\r\n");
    
          string postHeader = sb.ToString();
          byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
    
          // Build the trailing boundary string as a byte array
          // ensuring the boundary appears on a line by itself
          byte[] boundaryBytes =
              Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
    
          FileStream fileStream = new FileStream(uploadfile,
                        FileMode.Open, FileAccess.Read);
          long length = postHeaderBytes.Length + fileStream.Length +
                              boundaryBytes.Length;
          webrequest.ContentLength = length;
    
          Stream requestStream = webrequest.GetRequestStream();
    
          // Write out our post header
          requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
    
          // Write out the file contents
          byte[] buffer = new Byte[checked((uint)Math.Min(4096,
                       (int)fileStream.Length))];
          int bytesRead = 0;
          while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            requestStream.Write(buffer, 0, bytesRead);
    
          // Write out the trailing boundary
          requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
          WebResponse responce = webrequest.GetResponse();
          Stream s = responce.GetResponseStream();
          XmlSerializer xSerializer = new XmlSerializer(typeof(imginfo));
          imginfo ii = (imginfo)xSerializer.Deserialize(s);
          imginfoLinks ifl = ii.links;
          fileStream.Close();
          s.Close();
          return ifl.image_link;
          
    
        }
      }
    }
    

    the following is the XML deserialization class used in the above class

     

    using System.Xml.Serialization;
    
    namespace Imageshack
    {
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ns.imageshack.us/imginfo/7/", IsNullable = false)]
      public partial class imginfo
      {
    
        private imginfoRating ratingField;
    
        private imginfoFiles filesField;
    
        private imginfoResolution resolutionField;
    
        private string classField;
    
        private string visibilityField;
    
        private imginfoUploader uploaderField;
    
        private imginfoLinks linksField;
    
        private byte versionField;
    
        private uint timestampField;
    
        /// <remarks/>
        public imginfoRating rating
        {
          get
          {
            return this.ratingField;
          }
          set
          {
            this.ratingField = value;
          }
        }
    
        /// <remarks/>
        public imginfoFiles files
        {
          get
          {
            return this.filesField;
          }
          set
          {
            this.filesField = value;
          }
        }
    
        /// <remarks/>
        public imginfoResolution resolution
        {
          get
          {
            return this.resolutionField;
          }
          set
          {
            this.resolutionField = value;
          }
        }
    
        /// <remarks/>
        public string @class
        {
          get
          {
            return this.classField;
          }
          set
          {
            this.classField = value;
          }
        }
    
        /// <remarks/>
        public string visibility
        {
          get
          {
            return this.visibilityField;
          }
          set
          {
            this.visibilityField = value;
          }
        }
    
        /// <remarks/>
        public imginfoUploader uploader
        {
          get
          {
            return this.uploaderField;
          }
          set
          {
            this.uploaderField = value;
          }
        }
    
        /// <remarks/>
        public imginfoLinks links
        {
          get
          {
            return this.linksField;
          }
          set
          {
            this.linksField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public byte version
        {
          get
          {
            return this.versionField;
          }
          set
          {
            this.versionField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public uint timestamp
        {
          get
          {
            return this.timestampField;
          }
          set
          {
            this.timestampField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoRating
      {
    
        private byte ratingsField;
    
        private decimal avgField;
    
        /// <remarks/>
        public byte ratings
        {
          get
          {
            return this.ratingsField;
          }
          set
          {
            this.ratingsField = value;
          }
        }
    
        /// <remarks/>
        public decimal avg
        {
          get
          {
            return this.avgField;
          }
          set
          {
            this.avgField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoFiles
      {
    
        private imginfoFilesImage imageField;
    
        private imginfoFilesThumb thumbField;
    
        private ushort serverField;
    
        private ushort bucketField;
    
        /// <remarks/>
        public imginfoFilesImage image
        {
          get
          {
            return this.imageField;
          }
          set
          {
            this.imageField = value;
          }
        }
    
        /// <remarks/>
        public imginfoFilesThumb thumb
        {
          get
          {
            return this.thumbField;
          }
          set
          {
            this.thumbField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public ushort server
        {
          get
          {
            return this.serverField;
          }
          set
          {
            this.serverField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public ushort bucket
        {
          get
          {
            return this.bucketField;
          }
          set
          {
            this.bucketField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoFilesImage
      {
    
        private ushort sizeField;
    
        private string contenttypeField;
    
        private string valueField;
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public ushort size
        {
          get
          {
            return this.sizeField;
          }
          set
          {
            this.sizeField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute("content-type")]
        public string contenttype
        {
          get
          {
            return this.contenttypeField;
          }
          set
          {
            this.contenttypeField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlTextAttribute()]
        public string Value
        {
          get
          {
            return this.valueField;
          }
          set
          {
            this.valueField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoFilesThumb
      {
    
        private ushort sizeField;
    
        private string contenttypeField;
    
        private string valueField;
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public ushort size
        {
          get
          {
            return this.sizeField;
          }
          set
          {
            this.sizeField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute("content-type")]
        public string contenttype
        {
          get
          {
            return this.contenttypeField;
          }
          set
          {
            this.contenttypeField = value;
          }
        }
    
        /// <remarks/>
        [System.Xml.Serialization.XmlTextAttribute()]
        public string Value
        {
          get
          {
            return this.valueField;
          }
          set
          {
            this.valueField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoResolution
      {
    
        private ushort widthField;
    
        private ushort heightField;
    
        /// <remarks/>
        public ushort width
        {
          get
          {
            return this.widthField;
          }
          set
          {
            this.widthField = value;
          }
        }
    
        /// <remarks/>
        public ushort height
        {
          get
          {
            return this.heightField;
          }
          set
          {
            this.heightField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoUploader
      {
    
        private string ipField;
    
        /// <remarks/>
        public string ip
        {
          get
          {
            return this.ipField;
          }
          set
          {
            this.ipField = value;
          }
        }
      }
    
      /// <remarks/>
      [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
      [System.SerializableAttribute()]
      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.ComponentModel.DesignerCategoryAttribute("code")]
      [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
      public partial class imginfoLinks
      {
    
        private string image_linkField;
    
        private string image_htmlField;
    
        private string image_bbField;
    
        private string image_bb2Field;
    
        private string thumb_linkField;
    
        private string thumb_htmlField;
    
        private string thumb_bbField;
    
        private string thumb_bb2Field;
    
        private string yfrog_linkField;
    
        private string yfrog_thumbField;
    
        private string ad_linkField;
    
        private string done_pageField;
    
        /// <remarks/>
        public string image_link
        {
          get
          {
            return this.image_linkField;
          }
          set
          {
            this.image_linkField = value;
          }
        }
    
        /// <remarks/>
        public string image_html
        {
          get
          {
            return this.image_htmlField;
          }
          set
          {
            this.image_htmlField = value;
          }
        }
    
        /// <remarks/>
        public string image_bb
        {
          get
          {
            return this.image_bbField;
          }
          set
          {
            this.image_bbField = value;
          }
        }
    
        /// <remarks/>
        public string image_bb2
        {
          get
          {
            return this.image_bb2Field;
          }
          set
          {
            this.image_bb2Field = value;
          }
        }
    
        /// <remarks/>
        public string thumb_link
        {
          get
          {
            return this.thumb_linkField;
          }
          set
          {
            this.thumb_linkField = value;
          }
        }
    
        /// <remarks/>
        public string thumb_html
        {
          get
          {
            return this.thumb_htmlField;
          }
          set
          {
            this.thumb_htmlField = value;
          }
        }
    
        /// <remarks/>
        public string thumb_bb
        {
          get
          {
            return this.thumb_bbField;
          }
          set
          {
            this.thumb_bbField = value;
          }
        }
    
        /// <remarks/>
        public string thumb_bb2
        {
          get
          {
            return this.thumb_bb2Field;
          }
          set
          {
            this.thumb_bb2Field = value;
          }
        }
    
        /// <remarks/>
        public string yfrog_link
        {
          get
          {
            return this.yfrog_linkField;
          }
          set
          {
            this.yfrog_linkField = value;
          }
        }
    
        /// <remarks/>
        public string yfrog_thumb
        {
          get
          {
            return this.yfrog_thumbField;
          }
          set
          {
            this.yfrog_thumbField = value;
          }
        }
    
        /// <remarks/>
        public string ad_link
        {
          get
          {
            return this.ad_linkField;
          }
          set
          {
            this.ad_linkField = value;
          }
        }
    
        /// <remarks/>
        public string done_page
        {
          get
          {
            return this.done_pageField;
          }
          set
          {
            this.done_pageField = value;
          }
        }
      }
    }
    


    get C# code samples and tips at C# Programming help
    • Marked as answer by vamsi_krishna Monday, September 27, 2010 6:18 AM
    Monday, September 27, 2010 6:18 AM