title: How to catch a FtpWebResponse exception in C#
body: <p>I am building an FTP utility class in C#. In the case that a <code>WebException</code> is thrown on a call to <code>FtpWebRequest.GetResponse()</code>, in my case the exception is thrown for the requested file not existing on the remote server the <code>FtpWebResponse</code> variable is out of scope. </p>
  
  <p>But even if I declare the variable outside the <code>try..catch</code> block I get a compile error saying "Use of unassigned local variable 'response'", but as far as I can tell there is no way to assign it until you assign the response via the <code>FtpWebRequest.GetResponse()</code> method.</p>
  
  <p>Can someone please advise, or am I missing something obvious?</p>
  
  <p>Thanks!</p>
  
  <p><strong>Here is my current method:</strong></p>
  
  <pre><code>private void Download(string ftpServer, string ftpPath, string ftpFileName, string localPath, 
                             string localFileName, string ftpUserID, string ftpPassword)
      {
          FtpWebRequest reqFTP;
          FtpWebResponse response;
          try
          {
              reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://"
                 + ftpServer + "/" + ftpPath + "/" + ftpFileName));
              reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
              reqFTP.UseBinary = true;
              reqFTP.Credentials = new NetworkCredential(ftpUserID,
                                                         ftpPassword);
  
              /* HERE IS WHERE THE EXCEPTION IS THROWN FOR FILE NOT AVAILABLE*/
              response = (FtpWebResponse)reqFTP.GetResponse();
              Stream ftpStream = response.GetResponseStream();
  
  
              FileStream outputStream = new FileStream(localPath + "\\" +
                 localFileName, FileMode.Create);
  
              long cl = response.ContentLength;
              int bufferSize = 2048;
              int readCount;
              byte[] buffer = new byte[bufferSize];
  
              readCount = ftpStream.Read(buffer, 0, bufferSize);
              while (readCount &gt; 0)
              {
                  outputStream.Write(buffer, 0, readCount);
                  readCount = ftpStream.Read(buffer, 0, bufferSize);
              }
  
              ftpStream.Close();
              outputStream.Close();
              response.Close();
          }
          catch (WebException webex)
          {
              /*HERE THE response VARIABLE IS UNASSIGNED*/
              if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { 
                  //do something
              }
          }
  </code></pre>