fin*_*min 2 c# directory ftp exists
我有这个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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是调用它的方法,即使该目录不存在也返回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;
}
Run Code Online (Sandbox Code Playgroud)
希望有人能提供帮助.谢谢!:)
我找到了解决这个问题的方法.不是最好看,但它的工作原理.
也许这可以帮助其他人解决与我相同的问题.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我包含了GetFileList方法以回应Ray Chang的评论
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14508 次 |
| 最近记录: |