我正在用c_构建一个ftp实用程序类。在调用WebException
时调用FtpWebRequest.GetResponse()
的情况下,在我的情况下,针对远程服务器上不存在的请求文件抛出异常,FtpWebResponse
变量超出范围。
但是,即使我在try..catch
块之外声明变量,我也会得到一个编译错误,说“使用未分配的局部变量'response'”,但据我所知,在您通过FtpWebRequest.GetResponse()
方法分配响应之前,没有办法分配它。
有人能告诉我,还是我遗漏了一些显而易见的东西?
谢谢!
以下是我目前的方法:
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 > 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
}
}
最佳答案
作为解决此问题的通用方法,只需先将null
分配给响应,然后签入catch块(如果它null
)。
FtpWebResponse response = null;
try
{
...
}
catch (WebException webex)
{
if ((response != null) && (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)) {
//do something
}
}
但是,在这种特定情况下,您拥有
WebException
实例所需的所有属性(包括server response)!