I am creating an FTP utility class in C #. In the case when a WebException throws a call to FtpWebRequest.GetResponse() , in my case an exception is thrown for the requested file that does not exist on the remote server, the FtpWebResponse variable is out of scope.
But even if I declare a variable outside the try..catch block, I get a compilation error: "Using an unrecognized local variable" answer "", but as far as I can tell, there is no way to assign it until you assign the answer through the FtpWebRequest.GetResponse()
Can someone consult, or am I missing something obvious?
Thanks!
Here is my current method:
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); 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 > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); } catch (WebException webex) { if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) {
source share