gpt4 book ai didi

C# 检查 FTP 目录是否存在

转载 作者:行者123 更新时间:2023-11-30 19:42:51 25 4
gpt4 key购买 nike

我有这个 FTP 方法来检查目录是否存在。它在开始时工作正常,但现在,即使目录不存在,它仍然返回 true。我尝试了很多东西,并设置断点以查看我可以使用响应对象的哪些属性来确定目录是否存在。我还搜索了互联网,但解决方案似乎对我不起作用。这是我的 FTP 方法。

public bool directoryExists(string directory)
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
try
{
using (ftpRequest.GetResponse())
{
return true;
}
//var response = ftpRequest.GetResponse();
//if (response != null)
// return true;
//else return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}

/* Resource Cleanup */
finally
{
ftpRequest = null;
}
}

下面是调用它并返回 true 的方法,即使目录不存在也是如此:

private string getDirectory(ref FtpClass ftp, string internalID)
{
string remoteSubPathDel = internalID + "\\trunk\\prod\\xml\\delete";
string remoteSubPathUpdate = internalID + "\\trunk\\prod\\xml\\update";
string remoteSubPathNew = internalID + "\\trunk\\prod\\xml\\new";
if (ftp.directoryExists(remoteSubPathDel))
return remoteSubPathDel;
else if (ftp.directoryExists(remoteSubPathUpdate))
return remoteSubPathUpdate;
else if (ftp.directoryExists(remoteSubPathNew))
return remoteSubPathNew;
else
return String.Empty;
}

希望有人能帮忙。谢谢! :)

最佳答案

我找到了解决这个问题的方法。不是最好看的,但它确实有效。

也许这可以帮助其他人解决与我相同的问题。

public bool directoryExists2(string directory, string mainDirectory)
{
try
{
var list = this.GetFileList(mainDirectory);
if (list.Contains(directory))
return true;
else
return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}

编辑:我在回应 Ray Chang 的评论时包含了 GetFileList 方法

public string[] GetFileList(string path)
{
var ftpPath = host + "/" + path;
var ftpUser = user;
var ftpPass = pass;
var result = new StringBuilder();
try
{
var strLink = ftpPath;
var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(strLink));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(ftpUser, ftpPass);
reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
reqFtp.Proxy = null;
reqFtp.KeepAlive = false;
reqFtp.UsePassive = true;
using (var response = reqFtp.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
}
}
return result.ToString().Split('\n');
}
catch (Exception ex)
{
Console.WriteLine("FTP ERROR: ", ex.Message);
return null;
}

finally
{
ftpRequest = null;
}
}

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

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