Go to home page mail me! RSS Feed

Downloading a file using pure .Net Socket

Thursday, August 23, 2007 10:45 AM

Ok,  so sometimes HttpWebRequest and WebClient does not really cut it, so you have no choice but to perform a raw download - socket is the way to go. Here is a quick and dirty way of downloading a file using socket. .Net sockets are not limited to http, you can use it to download files from different protocols.

 

   1: // Local Variables
   2: string fileName = "/en/us/default.aspx";
   3: string hostName = "www.microsoft.com";
   4: string data = string.Empty;
   5: string dataFile = @"c:\temp\default.aspx";
   6: int port = 80;
   7: int bytes = 0, 
   8:     bytesCount = 0;
   9:  
  10: // IP Addresses
  11: IPAddress[] ips = Dns.GetHostEntry(hostName).AddressList;
  12:  
  13: // Instantiate the socket
  14: System.Net.Sockets.Socket
  15:     sck = new System.Net.Sockets.Socket(Dns.GetHostEntry(hostName)
  16:     .AddressList[0].AddressFamily,
  17:      System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
  18:  
  19: try
  20: {
  21:     // Connect to the host, using the specified port
  22:     sck.Connect(hostName, port);
  23:  
  24:     // Its all good!
  25:     if (sck != null && sck.Connected)
  26:     {
  27:         try
  28:         {
  29:             string dataReq = string.Format("GET {0} HTTP/1.1\r\n", fileName);
  30:             dataReq += "Host: blog.DotNetClr.com\r\n";
  31:             //Note the double line - required!
  32:             dataReq += "Connection: Close\r\n\r\n"; 
  33:  
  34:             // Our Bytes
  35:             Byte[] bytesSent = Encoding.ASCII.GetBytes(dataReq);
  36:  
  37:             // You may increase the size of the receive buffer if 
  38:             // you need to - wouldn't recommend it though!
  39:             Byte[] bytesReceived = new Byte[256]; 
  40:  
  41:             // Send the request to the server
  42:             int byteCount = sck.Send(bytesSent, 
  43:                 bytesSent.Length, System.Net.Sockets.SocketFlags.None);
  44:             Console.WriteLine("Sent {0} bytes to host.", byteCount);
  45:  
  46:             // Wait until all bytes from the response has been received.
  47:             do
  48:             {
  49:                 bytes = sck.Receive(bytesReceived, System.Net.Sockets.SocketFlags.None);
  50:                 bytesCount += bytes;
  51:                 data += Encoding.UTF8.GetString(bytesReceived);
  52:                 Console.WriteLine("Received " + bytesCount.ToString() + " bytes so far.");
  53:             }
  54:             while (bytes > 0);
  55:         }
  56:         catch (System.Net.Sockets.SocketException e)
  57:         {
  58:             Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode);
  59:             sck.Close();
  60:         }
  61:         finally
  62:         {
  63:             //TODO: You may want to trap errors here and do more, this is just a DEMO.
  64:             if (data.Length > 0)
  65:             {
  66:                 System.IO.FileStream fs = System.IO.File.OpenWrite(dataFile);
  67:                 fs.Write(Encoding.UTF8.GetBytes(data), 0, bytesCount);
  68:                 fs.Close();
  69:             }
  70:         }
  71:  
  72:     }
  73:     else
  74:     {
  75:         Console.WriteLine("Unable to connect to the specified host.");
  76:     }
  77: }
  78: catch(Exception ex)
  79: {
  80:     //TODO: Take action here.
  81: }
  82: finally
  83: {
  84:     // Close the socket if its still open.
  85:     if(sck.Connected)
  86:         sck.Close();
  87: }
  88:  
  89: Console.WriteLine("Done! Press Any Key To Exit");
  90: Console.ReadKey();

Your Comments.

No comments posted yet.

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 1 and 3 and type the answer here:

Preview Your Comment.

 
Next entries »