gpt4 book ai didi

c# - 如何检查FTP目录是否存在

转载 作者:IT王子 更新时间:2023-10-29 04:12:55 25 4
gpt4 key购买 nike

寻找通过 FTP 检查给定目录的最佳方法。

目前我有以下代码:

private bool FtpDirectoryExists(string directory, string username, string password)
{

try
{
var request = (FtpWebRequest)WebRequest.Create(directory);
request.Credentials = new NetworkCredential(username, password);
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
return false;
else
return true;
}
return true;
}

无论目录是否存在,都会返回 false。有人能指出我正确的方向吗。

最佳答案

基本上捕获了我在创建目录时收到的错误。

private bool CreateFTPDirectory(string directory) {

try
{
//create the directory
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(new Uri(directory));
requestDir.Method = WebRequestMethods.Ftp.MakeDirectory;
requestDir.Credentials = new NetworkCredential("username", "password");
requestDir.UsePassive = true;
requestDir.UseBinary = true;
requestDir.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)requestDir.GetResponse();
Stream ftpStream = response.GetResponseStream();

ftpStream.Close();
response.Close();

return true;
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
response.Close();
return true;
}
else
{
response.Close();
return false;
}
}
}

关于c# - 如何检查FTP目录是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2769137/

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