我用ftp下载execl,能下载,但是都是0kb,断点进去之后是 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();这句之后就不执行,请问是啥原因呢
public void DownloadFile( string fileName)
{
FtpWebRequest reqFTP;
try
{
FileStream fileStream = new FileStream(Environment.CurrentDirectory + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://192.168.0.247:1356/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential("ftp2023", "powev888888");
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();//从ftp响应中获得响应流
//long cl = response.ContentLength;
byte[] buffer = new byte[1024];
int readCount;
readCount = responseStream.Read(buffer, 0, buffer.Length);//从ftp的responseStream读取数据到buffer中
while (readCount > 0)
{
fileStream.Write(buffer, 0, readCount);//从buffer读取数据到fileStream中,完成下载
readCount = responseStream.Read(buffer, 0, buffer.Length);
}
responseStream.Close();
fileStream.Close();
response.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
但是如果在执行FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse()时出现异常,就会导致控制流不会继续往下执行。可以在该语句之前添加一个try-catch块,以便在发生错误时捕获它并打印错误信息,以便更好地了解错误原因。
try
{
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
// 剩余代码
}
catch (WebException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
在这里,ex.Message将包含错误信息,这有助于了解导致错误的原因。
此外还可以在该语句之前添加一个if语句,检查FTP服务器是否成功响应:
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
if (response.StatusCode == FtpStatusCode.ClosingData)
{
// 剩余代码
}
else
{
Console.WriteLine("Error: " + response.StatusDescription);
}
在这里,response.StatusDescription将包含有关错误的信息。
仅供参考,望采纳,谢谢。