title: Save a file downloaded via WinHTTP to disk, using Delphi XE
body: <p>An answer to <a href="https://stackoverflow.com/questions/6725348/winhttp-delphi-wrapper">this question</a> showed how easy it is to use WinHTTP via Type Library imports in delphi.</p>
  
  <p>I imported the type library for WinHTTP, and then tried to write a File Download helper function using that api. Here's how far I got:</p>
  
  <p>I can't seem to figure out how to save the IWinHttpRequest.ResponseStream (declared as OleVariant in the TLB file) as Stream, to disk.</p>
  
  <pre><code>// IWinHttpRequest is defined by importing type library of WinHTTP.
  // Microsoft WinHTTP Services, version 5.1 (Version 5.1) C:\Windows\system32\winhttp.dll
  function Download(const url, filename: String): Boolean;
  var
     http: IWinHttpRequest;
     wUrl: WideString;
     fs:TFileStream;
     FileStream:IStream;
     sz,rd,wr:Int64;
  begin
    try
     wUrl := url;
     http := CoWinHttpRequest.Create;
     http.open('GET', wurl, False);
     http.send(EmptyParam);
  
     FStatus := http.status; // 200=OK!
     result := FStatus=200;
  
  
     if result then
     begin
       fs := TFileStream.Create(filename, fmCreate, fmShareExclusive );
       try
        FileStream := TStreamAdapter.Create(fs, soReference) as IStream;
        sz := http.ResponseStream.Size;
        http.ResponseStream.CopyTo(FileStream,sz,rd,wr);
       finally
           FileStream :=  nil;
           fs.Free;
       end;
     end;
    except
        result := false;
        // do not raise exceptions.
    end;
  end;
  </code></pre>
  
  <p>Excerpt from WinHTTP_TLB.pas:</p>
  
  <pre><code> IWinHttpRequest = interface(IDispatch)
      ['{016FE2EC-B2C8-45F8-B23B-39E53A75396B}']
      ......
      property ResponseStream: OleVariant read Get_ResponseStream;
  </code></pre>
  
  <p>Update: I now get a runtime exception about ole variants, at the call to <code>http.ResponseStream.CopyTo(...)</code></p>
  
  <pre><code> EOleError 'Variant does not reference an automation object'.
  </code></pre>