title: Upload File With Powershell using Response Stream
body: <p>I'm having a problem here trying to upload a file with powershell.  What I'm trying to do is shoot a .zip file to a target user account on a destination server.  Destination server is running IIS FTP 7.5 and has user isolation enabled with a datachannel port range of 5500-6500 (if that might matter).</p>
  
  <p>Here's my code below - the problem is I get that I cannot call a method on a null-valued expression on the <code>$responsestream</code> request.  Please let me know if I goofed up, looking all over the net... have had so many problems uploading files!</p>
  
  <p>Also I want to say I used a download script that I'm converting to upload since I haven't had any success with the upload scripts I've tried out before.  </p>
  
  <pre><code>$targetpath = "ftp://10.21.109.202/Recieve/account_apps.zip"
  $sourceuri = "D:\AccountManager\Send\$RTMPHOST\account_apps.zip"
  $username = "AccountManager"
  $password = "test"
  
  # Create a FTPWebRequest object to handle the connection to the ftp server
  $ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)
  
  # set the request's network credentials for"
  
  #an authenticated connection
  $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)
  
  $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
  $ftprequest.UseBinary = $true
  $ftprequest.KeepAlive = $false
  
  # send the ftp request to the server
  $ftpresponse = $ftprequest.GetResponse()
  
  # get a download stream from the server response
  $responsestream = $ftpresponse.GetRequestStream()
  
  # create the target file on the local system and the download buffer
  $targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)
  [byte[]]$readbuffer = New-Object byte[] 1024
  
  # loop through the download stream and send the data to the target file
  do{
      $readlength = $responsestream.Read($readbuffer,0,1024)
      $targetfile.Write($readbuffer,0,$readlength)
  }
  while ($readlength -ne 0)
  
  $targetfile.close()
  </code></pre>