gpt4 book ai didi

c# - 下载前检查文件在ftp服务器上是否存在

转载 作者:太空宇宙 更新时间:2023-11-03 11:46:21 25 4
gpt4 key购买 nike

从ftp服务器下载一个文件之前,我想检查它是否存在,如果不存在则must 抛出异常。当文件不存在时,代码示例有效。但是,当文件存在时,执行该行后; "ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;"它跳到第二个 catch block 并打印“错误:提交请求后无法执行此操作。”我看不到的重点是什么..感谢您的回答。

public void fileDownload(string fileName)
{
stream = new FileStream(filePath + fileName, FileMode.Create);
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
ftpRequest.Credentials = new NetworkCredential(userName, password);
ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;

try
{
response = (FtpWebResponse)ftpRequest.GetResponse();
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpRequest.UseBinary = true;
response = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = response.GetResponseStream();
cl = response.ContentLength;
bufferSize = 2048;
buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);

while (readCount > 0)
{
stream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}

ftpStream.Close();
stream.Close();
response.Close();
Console.WriteLine("File : " + fileName + " is downloaded from ftp server");
}
catch (WebException ex)
{
FtpWebResponse res = (FtpWebResponse)ex.Response;
if (res.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
stream.Close();
File.Delete(filePath + fileName);
Console.WriteLine("File : " + fileName + " does not exists on ftp server");
System.Diagnostics.Debug.WriteLine("Error: " + fileName + " is not available on fpt server");
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error: " + ex.Message);
}
}

最佳答案

我的理解是您必须为您发出的每个请求创建一个新的 FtpWebRequest。因此,在再次设置 Method 之前,您必须创建一个新方法并再次设置凭据。如此之多以至于您不得不重复以下两行:

ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
ftpRequest.Credentials = new NetworkCredential(userName, password);

关于c# - 下载前检查文件在ftp服务器上是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3335019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com