try-catch-finally 变量作用域的问题 在线等
private void Download(string filePath, string fileName, string localfileName)
{
try
{
FtpWebRequest reqFTP;
FileStream outputStream;
FtpWebResponse response;
Stream ftpStream;
outputStream = new FileStream(filePath + "\\" + localfileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream();
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);
}
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message());
}
finally
{
ftpStream.Close();
outputStream.Close();
response.Close();
}
}
为什么编译之后 finally中 的三个要关闭的资源变量报错 提示ftpStream,outputStream,response未定义.
如果放到把定义这三个对象放在try上面 就说未附值.
难道在try中定义的变量或者对象 作用域只在try 中吗 ?
------解决方案--------------------
private void Download(string filePath, string fileName, string localfileName)
{
FileStream outputStream;
FtpWebResponse response;
Stream ftpStream;
try
{
FtpWebRequest reqFTP;
outputStream = new FileStream(filePath + "\\" + localfileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream();
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);
}
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message());
}
finally
{
ftpStream.Clo