我正在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
}
}发布于 2010-03-11 10:29:33
作为解决这一问题的一般方法,只需首先将null分配给响应,然后签入catch块(如果为null )。
FtpWebResponse response = null;
try
{
...
}
catch (WebException webex)
{
if ((response != null) && (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)) {
//do something
}
}但是,在这种特殊情况下,您拥有WebException实例(包括服务器响应 )所需的所有属性!
发布于 2010-04-21 06:11:57
在这个问题中可以找到正确的解决办法:
如何在FtpWebRequest之前检查FTP上是否存在文件
简言之:
由于错误,您的“响应”变量将始终为空。您需要从‘FtpWebResponse’(强制转换它)中测试webex.Response以获得StatusCode。
发布于 2010-03-11 10:29:37
那么,您可以始终赋值一个变量:
FtpWebRequest reqFTP = null;
FtpWebResponse response = null;https://stackoverflow.com/questions/2424154
复制相似问题