title: Multithreaded TIdHTTP file download with filestream results in corrupted file
body: <p>I've followed quite a few examples of creating a multithreaded file-download using TIdHTTP component, but I'm stumped with the following problem:</p>
  
  <p>But first, a simplified version of my code. </p>
  
  <p>This part calculates the size of the file that needs to be downloaded:</p>
  
  <pre><code>TIdHTTP* tcpClient = new TIdHTTP(NULL);
  tcpClient-&gt;ProtocolVersion = pv1_1;
  tcpClient-&gt;Head(URL);
  __int64 LSize = tcpClient-&gt;Response-&gt;ContentLength;
  System::Classes::TFileStream *STFile = new System::Classes::TFileStream(FFileName, fmCreate);
  try
  {
      STFile-&gt;Size = LSize;
  }
  __finally
  {
      delete STFile;
  };
  delete tcpClient;
  </code></pre>
  
  <p>Next is a part of the Execute method of a thread that gets called multiple times by my MainForm. FStartPos is the start position in the file for that thread (i.o.w first thread starts at position 0), FEndPos is the end of the block that needs to be retrieved:</p>
  
  <pre><code>TFileStream *LStream = new TFileStream(FFileName, fmOpenWrite | fmShareDenyNone);
  LHttpClient = new TIdHTTP(NULL);
  LHttpClient-&gt;ProtocolVersion = pv1_1;
  LHttpClient-&gt;Request-&gt;BasicAuthentication = true;
  LHttpClient-&gt;Request-&gt;Username = FUsername;
  LHttpClient-&gt;Request-&gt;Password = FPassword;
  try
  {
      LHttpClient-&gt;OnWork = ReceiveDataEvent;
      try
      {
      try
      {
        LStream-&gt;Seek(FStartPos, TSeekOrigin::soBeginning);
        LHttpClient-&gt;Request-&gt;Range = "bytes="+UnicodeString(FStartPos)+"-"+UnicodeString(FEndPos);
        LHttpClient-&gt;Get(URL, LStream);
        IsFin = true;
      } catch(Exception &amp;e)
      {
          // log the error
      }
      }
      __finally
      {
          LHttpClient-&gt;Disconnect();
          delete LHttpClient;
      }
  }
  __finally
  {
      delete LStream;
  }
  </code></pre>
  
  <p>When I try to download e.g. an 87MB file, I create 5 download threads, so each thread should be downloading 17MB odd. What I see happening, is that the file gets created (and reports 87MB in size). Usually thread number 3 finishes first, and the file size jumps to 52MB, then thread 1 finishes and the file size jumps to 17MB, and lastly thread 4 finishes with the file now at 69MB (instead of the 87MB is started as).</p>
  
  <p>I have a feeling I'm either using TFileStream incorrectly, or using it in a way that it wasn't designed to be used in.</p>
  
  <p>My question is, is my code wrong? Or is there a better / more appropriate way to write from multiple threads to a single file, but each in its own block?</p>
  
  <p>(I'm running C++ Builder 10.1 with the built in Indy 10 I think)</p>
  
  <p>Thanks in advance for any advice.</p>
  
  <p>-G-</p>