我正在用 C# 构建一个 FTP 实用程序类。如果在WebException
调用 时抛出 a FtpWebRequest.GetResponse()
,在我的情况下,对于远程服务器上不存在的请求文件抛出异常,该FtpWebResponse
变量超出范围。
但是,即使我在try..catch
块之外声明变量,我也会收到一个编译错误,说“使用未分配的局部变量'响应'”,但据我所知,在您通过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
}
}