Hi Guys,
I am developing an windows application which is downloading file from webserver using FTP, my question is can i download file using HTTP. can anybody help me with some source. I am downloading a xml file.


Thanks in advance.

Dani AI

Generated

Yes. For a Windows app pulling an XML from a web server, prefer HttpClient over the older WebClient/HttpWebRequest shown by . In modern .NET (6+), WebRequest/WebClient are obsolete and HttpClient is the recommended API. Reuse a single HttpClient (or use IHttpClientFactory) to avoid socket exhaustion. (learn.microsoft.com)

Quick, memory-safe download that streams directly to disk and works well for large files:

using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

static class Downloader
{
    // Reuse one client for the lifetime of the app.
    private static readonly HttpClient http = new HttpClient();

    public static async Task<string> DownloadXmlAsync(string url, string destinationFolder, CancellationToken ct = default)
    {
        using var resp = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
        resp.EnsureSuccessStatusCode();

        // Prefer server-provided file name when available.
        var cd = resp.Content.Headers.ContentDisposition;
        var fileName = cd?.FileNameStar ?? cd?.FileName?.Trim('"') 
                       ?? Path.GetFileName(new Uri(url).AbsolutePath);

        var path = Path.Combine(destinationFolder, string.IsNullOrWhiteSpace(fileName) ? "download.xml" : fileName);

        await using var src = await resp.Content.ReadAsStreamAsync(ct);
        await using var dst = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 81920, useAsync: true);
        await src.CopyToAsync(dst, ct);

        return path;
    }
}

Notes and tips:

  • ResponseHeadersRead streams the body instead of buffering it; when you use it, HttpClient.Timeout applies only until headers arrive, so pass a CancellationToken to bound the copy, as above. (learn.microsoft.com)
  • If the server sets Content-Disposition, make sure filenames with spaces are quoted or provided via filename*; otherwise parsers may ignore them and you should fall back to the URL path as shown. (developer.mozilla.org)

This approach complements ’s answer while aligning with current .NET guidance. (learn.microsoft.com)

Recommended Answers

All 3 Replies

You could do something like this:

using System.IO;
using System.Net;

namespace DW_413504_CS_CON
{
   class Program
   {
      public static void DoWebClientExample(string strURI)
      {
         WebClient wc = new WebClient();
         wc.DownloadFile(strURI, "c:\\install\\txpeng542.exe");
      }

      static void Main(string[] args)
      {
         string strURI = "";

         DoWebClientExample(strURI);
      }
   }
}

I made this example using an EXE file which demonstrates the continuity of the download, but it will work either way, but if your file is XML, you could just use the web client method.
Here are examples of both WebClient and HTTPWebRequest (downloads will go into the current user's temp directory):

using System;
using System.IO;
using System.Linq;
using System.Net;

namespace DW_413504_CS_CON
{
   class Program
   {
      public static string _strTempDir = Path.GetTempPath();

      public static void DoWebClientExample(string strURI)
      {
         WebClient wc = new WebClient();
         string strFileName = strURI.Split('/').Last();
         wc.DownloadFile(strURI, Path.Combine(_strTempDir, strFileName));
      }

      public static bool DownloadFile(HttpWebResponse resp, string strFileName, ref string strError)
      {
         bool blnRetVal = true;

         try
         {
            long lngFileSize = resp.ContentLength;

            using (StreamReader fileIn = new StreamReader(resp.GetResponseStream()))
            {
               using (StreamWriter fileOut = new StreamWriter(strFileName))
               {
                  long lngTotalBytesRead = 0;
                  int intBytesRead = 0;

                  byte[] buff = new byte[8192];//size based on observation*2

                  for (int intLoop = 0; lngTotalBytesRead < lngFileSize; intLoop++)
                  {
                     intBytesRead = fileIn.BaseStream.Read(buff, 0, buff.Length);
                     fileOut.BaseStream.Write(buff, 0, intBytesRead);
                     lngTotalBytesRead += intBytesRead;
                  }
                  //
                  fileOut.Flush();
                  fileOut.Close();
               }
               //
               fileIn.Close();
            }
            //
            resp.Close();
         }
         catch (Exception exc)
         {
            blnRetVal = false;
            strError = exc.Message;
         }

         return blnRetVal;
      }

      public static bool DoWebRequestExample(string strURI, ref string strError)
      {
         bool blnRetVal = true;
         try
         {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strURI);
            req.Method = WebRequestMethods.Http.Get;
            using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
            {
               string strFileName = strURI.Split('/').Last();
               if (!DownloadFile(resp, Path.Combine(_strTempDir, strFileName), ref strError))
               {
                  blnRetVal = false;
               }
               //
               resp.Close();
            }
         }
         catch (Exception exc)
         {
            blnRetVal = false;
            strError = exc.Message;
         }

         return blnRetVal;
      }

      static void Main(string[] args)
      {
         string strError = "";
         string strURI = "";
         
         if (!DoWebRequestExample(strURI, ref strError))
         {
            Console.WriteLine("Could not download file: " + strError);
            return;
         }

         DoWebClientExample(strURI);
      }
   }
}

Thanks thines01.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.