Download and save the file from the http server using .Net Socket

Greetings to all.

I would like to know how to download and save a file on my hard drive, in particular a file zipfrom an HTTP server, using the class System.Net.Socket.Sockets.

I know that there are easier ways to download a file from .Net, but I would like to know how to do it with Sockets , if possible, of course, although I am sure that it is.

I tried several things, nothing worked when I have no experience with sockets.

Your help, satisfying my curiosity, is appreciated. Any question is just asking. Thank.

Note

  • The file is a standard zip file, however I would like it to work with any type of file.
  • File size is different every day.
  • The file is downloaded every minute, so caching of such a file must be disabled in order to get the exact version of the update file from the server.
  • Example URL file: www.somewhere.com/files/feed/list.zip
+3
source share
2 answers

You can do this directly using a .NET socket, but this will require a parsing and understanding of the HTTP request.

The standard way to do this is simply to use higher-level System.Net classes. For example, this can be done in two lines of code through WebClient.DownloadFile - why is life getting more difficult for you?


, . 80 (, http) TCP-, .

, , StackOverflow. , HTTP - .

+3

"HttpWebRequest" "HttpWebResponse" .net.

, , , .

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "www.somewhere.com/files/feed/list.zip";       
            string fileName = @"C:\list.zip";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 5000;

            try
            {
                using (WebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                    {
                        byte[] bytes = ReadFully(response.GetResponseStream());

                        stream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (WebException)
            {
                Console.WriteLine("Error Occured");
            }
        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    }
}

!

+1

Source: https://habr.com/ru/post/1768338/


All Articles