[Mono-list] HTTP file download

Gonzalo Paniagua Javier gonzalo.mono at gmail.com
Sun Apr 26 11:17:09 EDT 2009


On Fri, 2009-04-24 at 14:05 -0700, giancarlogiesa wrote:
> Hello,
> 
> is possible with C# / Mono download a file from an HTTP server ?
> if yes, how ?
> 
> my code is this:
> ------------------------------------
>     private string SocketSendReceive(string url){
> 		int i=0;
> 		while(i<url.Length && url[i]!='/'){
> 			i++;
> 		}
> 		string server=url.Substring(0,i);
> 		string request = "GET "+url.Substring(i)+" HTTP/1.1\r\nHost: " + server +
> "\r\nConnection: Close\r\n\r\n";
>         Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
>         Byte[] bytesReceived = new Byte[1024];
>         Socket s = ConnectSocket(server, 80);
>         if (s == null){
>             return ("Connection failed");
> 		}
>         s.Send(bytesSent, bytesSent.Length, 0);  
> 			
>         int bytes = 0;
>         string page = null;
>         do {
>             bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
>             page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);

You are using ASCII encoding. That's why downloading a Zip file fails.
If you're going to roll your own HTTP download instead of using
HttpWebRequest/WebClient you should check the Content-Type and "decode"
the incoming stream according to the type.

-Gonzalo




More information about the Mono-list mailing list