SoFunction
Updated on 2025-03-07

C# method to implement multi-threaded file download

This article describes the method of C# to implement multi-threaded files. Share it for your reference. The specific implementation method is as follows:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
namespace WfpApp
{
 public class MultiDownload
 {
  #region variable  private int _threadNum;    //Number of threads  private long _fileSize;    //File size  private string _fileUrl;   //File address  private string _fileName;   //file name  private string _savePath;   //Save path  private short _threadCompleteNum; //The number of threads completed  private bool _isComplete;   //Is it done  private volatile int _downloadSize; //Current download size (real time)  private Thread[] _thread;   //Thread array  private List<string> _tempFiles = new List<string>();
  private object locker = new object();
  #endregion
  #region properties  /// <summary>
  /// file name  /// </summary>
  public string FileName
  {
   get
   {
    return _fileName;
   }
   set
   {
    _fileName = value;
   }
  }
  /// <summary>
  /// File size  /// </summary>
  public long FileSize
  {
   get
   {
    return _fileSize;
   }
  }
  /// <summary>
  /// Current download size (real time)  /// </summary>
  public int DownloadSize
  {
   get
   {
    return _downloadSize;
   }
  }
  /// <summary>
  /// Whether it is completed  /// </summary>
  public bool IsComplete
  {
   get
   {
    return _isComplete;
   }
  }
  /// <summary>
  /// Number of threads  /// </summary>
  public int ThreadNum
  {
   get
   {
    return _threadNum;
   }
  }
  /// <summary>
  /// Save the path  /// </summary>
  public string SavePath
  {
   get
   {
    return _savePath;
   }
   set
   {
    _savePath = value;
   }
  }
  #endregion
  /// <summary>
  /// Constructor  /// </summary>
  /// <param name="threahNum">Number of threads</param>  /// <param name="fileUrl">File Url path</param>  /// <param name="savePath">Local save path</param>  public MultiDownload(int threahNum, string fileUrl, string savePath)
  {
   this._threadNum = threahNum;
   this._thread = new Thread[threahNum];
   this._fileUrl = fileUrl;
   this._savePath = savePath;
  }
  public void Start()
  {
   HttpWebRequest request = (HttpWebRequest)(_fileUrl);
   HttpWebResponse response = (HttpWebResponse)();
   _fileSize = ;
   int singelNum = (int)(_fileSize / _threadNum);  //Average distribution   int remainder = (int)(_fileSize % _threadNum);  //Get the remaining ones   ();
   ();
   for (int i = 0; i &lt; _threadNum; i++)
   {
    List&lt;int&gt; range = new List&lt;int&gt;();
    (i * singelNum);
    if (remainder != 0 &amp;&amp; (_threadNum - 1) == i) //Leave the rest to the last thread     (i * singelNum + singelNum + remainder - 1);
    else
     (i * singelNum + singelNum - 1);
    //Download data at the specified location    int[] ran = new int[] { range[0], range[1] };
    _thread[i] = new Thread(new ParameterizedThreadStart(Download));
    _thread[i].Name = (_fileUrl) + "_{0}".Replace("{0}", (i + 1));
    _thread[i].Start(ran);
   }
  }
  private void Download(object obj)
  {
   Stream httpFileStream = null, localFileStram = null;
   try
   {
    int[] ran = obj as int[];
    string tmpFileBlock = () +  + ".tmp";
    _tempFiles.Add(tmpFileBlock);
    HttpWebRequest httprequest = (HttpWebRequest)(_fileUrl);
    (ran[0], ran[1]);
    HttpWebResponse httpresponse = (HttpWebResponse)();
    httpFileStream = ();
    localFileStram = new FileStream(tmpFileBlock, );
    byte[] by = new byte[5000];
    int getByteSize = (by, 0, (int)); //Read method will return the total number of bytes read into the by variable    while (getByteSize &gt; 0)
    {
     (20);
     lock (locker) _downloadSize += getByteSize;
     (by, 0, getByteSize);
     getByteSize = (by, 0, (int));
    }
    lock (locker) _threadCompleteNum++;
   }
   catch (Exception ex)
   {
    throw new Exception(());
   }
   finally
   {
    if (httpFileStream != null) ();
    if (localFileStram != null) ();
   }
   if (_threadCompleteNum == _threadNum)
   {
    Complete();
    _isComplete = true;
   }
  }
  /// &lt;summary&gt;
  /// Merge file blocks after downloading  /// &lt;/summary&gt;
  private void Complete()
  {
   Stream mergeFile = new FileStream(@_savePath, );
   BinaryWriter AddWriter = new BinaryWriter(mergeFile);
   foreach (string file in _tempFiles)
   {
    using (FileStream fs = new FileStream(file, ))
    {
     BinaryReader TempReader = new BinaryReader(fs);
     (((int)));
     ();
    }
    (file);
   }
   ();
  }
 }
}

Called:

string httpUrl = @"http://172.28.98.96/fdimsservice/";
string saveUrl = () + "//" + (httpUrl);
int threadNumber = 5;
MultiDownload md = new MultiDownload(threadNumber, httpUrl, saveUrl);
();

I hope this article will be helpful to everyone's C# programming.