C# 如何检查FTP目录是否存在
寻找通过FTP检查给定目录的最佳方法 目前我有以下代码:C# 如何检查FTP目录是否存在,c#,.net,ftp,ftpwebrequest,C#,.net,Ftp,Ftpwebrequest,寻找通过FTP检查给定目录的最佳方法 目前我有以下代码: private bool FtpDirectoryExists(string directory, string username, string password) { try { var request = (FtpWebRequest)WebRequest.Create(directory); request.Credentials = new NetworkCredential(u
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。有人能给我指出正确的方向吗。导航到父目录,执行“ls”命令,并解析结果。如果您使用该组件,您的FTP生活将变得更加轻松。它是免费的,因为它处理命令和响应,所以可以省去你们的麻烦。您只需使用一个漂亮、简单的对象。基本上捕获了我在创建这样的目录时收到的错误
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;
}
}
}
我无法让@BillyLogans的建议生效 我发现问题是默认的FTP目录是/home/usr/fred 当我使用:
String directory = "ftp://some.domain.com/mydirectory"
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(new Uri(directory));
我发现这个变成了
"ftp:/some.domain.com/home/usr/fred/mydirectory"
要停止此操作,请将目录Uri更改为:
String directory = "ftp://some.domain.com//mydirectory"
然后这就开始起作用了。我会尝试以下方法:
- 发送MLST FTP命令(在RFC3659中定义)并解析其输出。它应该返回包含现有目录的目录详细信息的有效行
- 如果MLST命令不可用,请尝试使用CWD命令将工作目录更改为测试目录。在更改到测试目录以便能够返回之前,不要忘记确定当前路径(PWD命令)
- 在某些服务器上,MDTM和SIZE命令的组合可以用于类似的目的,但其行为非常复杂,超出了本文的范围
string path = "/path/to/directory";
Rebex.Net.Ftp ftp = new Rebex.Net.Ftp();
ftp.Connect("hostname");
ftp.Login("username","password");
Console.WriteLine(
"Directory '{0}' exists: {1}",
path,
ftp.DirectoryExists(path)
);
ftp.Disconnect();
使用此代码,它可能是您的答案
public bool FtpDirectoryExists(string directoryPath, string ftpUser, string ftpPassword)
{
bool IsExists = true;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(directoryPath);
request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
request.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
IsExists = false;
}
return IsExists;
}
我将此方法称为:
bool result = FtpActions.Default.FtpDirectoryExists( @"ftp://mydomain.com/abcdir", txtUsername.Text, txtPassword.Text);
为什么要使用另一个库-创建您自己的逻辑。我尝试了各种方法以获得可靠的检查,但
WebRequestMethods.Ftp.PrintWorkingDirectory
和WebRequestMethods.Ftp.ListDirectory
方法都不能正常工作。检查ftp:///Logs
服务器上不存在,但他们说有
所以我想出的方法是尝试上传到文件夹。但是,有一个“gotcha”是您可以在这个线程中阅读的路径格式
下面是一段代码片段
private bool DirectoryExists(string d)
{
bool exists = true;
try
{
string file = "directoryexists.test";
string path = url + homepath + d + "/" + file;
//eg ftp://website//home/directory1/directoryexists.test
//Note the double space before the home is not a mistake
//Try to save to the directory
req = (FtpWebRequest)WebRequest.Create(path);
req.ConnectionGroupName = "conngroup1";
req.Method = WebRequestMethods.Ftp.UploadFile;
if (nc != null) req.Credentials = nc;
if (cbSSL.Checked) req.EnableSsl = true;
req.Timeout = 10000;
byte[] fileContents = System.Text.Encoding.Unicode.GetBytes("SAFE TO DELETE");
req.ContentLength = fileContents.Length;
Stream s = req.GetRequestStream();
s.Write(fileContents, 0, fileContents.Length);
s.Close();
//Delete file if successful
req = (FtpWebRequest)WebRequest.Create(path);
req.ConnectionGroupName = "conngroup1";
req.Method = WebRequestMethods.Ftp.DeleteFile;
if (nc != null) req.Credentials = nc;
if (cbSSL.Checked) req.EnableSsl = true;
req.Timeout = 10000;
res = (FtpWebResponse)req.GetResponse();
res.Close();
}
catch (WebException ex)
{
exists = false;
}
return exists;
}
我假设您已经对FtpWebRequest有些熟悉,因为这是在.NET中访问FTP的常用方法 您可以尝试列出目录并检查错误状态代码
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.microsoft.com/12345");
request.Method = WebRequestMethods.Ftp.ListDirectory;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
// Okay.
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
// Directory not found.
}
}
}
我也遇到了类似的问题。我用的是
FtpWebRequest=(FtpWebRequest)WebRequest.Create(“ftp://ftpserver.com/rootdir/test_if_exist_directory");
request.Method=WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response=(FtpWebResponse)request.GetResponse();
并等待一个异常,以防目录不存在。此方法未引发异常
经过几次尝试,我将目录更改为:
"ftp://ftpserver.com/rootdir/test_if_exist_directory“至:”ftp://ftpserver.com/rootdir/test_if_exist_directory/". 现在代码对我有用了
我认为我们应该将forwardslash(/)附加到ftp文件夹的URI中,以使其正常工作
根据要求,完整的解决方案现在将是:
public bool doesfpdirectoryExist(字符串dirPath)
{
尝试
{
FtpWebRequest=(FtpWebRequest)WebRequest.Create(dirPath);
request.Method=WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response=(FtpWebResponse)request.GetResponse();
返回true;
}
捕获(WebException ex)
{
返回false;
}
}
//调用该方法(请注意路径末尾的正斜杠):
字符串ftpDirectory=”ftp://ftpserver.com/rootdir/test_if_exist_directory/";
bool dirExists=DoesFtpDirectoryExist(ftpDirectory);
对我来说唯一有效的方法是反向逻辑,尝试创建目录/路径(如果已经存在,将抛出异常),如果已经存在,则再次删除。否则,使用异常设置一个标志,表示目录/路径存在。我是VB.NET新手,我是舒尔,有一种更好的方法来编写此代码-但无论如何,我的代码如下:
Public Function DirectoryExists(directory As String) As Boolean
' Reversed Logic to check if a Directory exists on FTP-Server by creating the Directory/Path
' which will throw an exception if the Directory already exists. Otherwise create and delete the Directory
' Adjust Paths
Dim path As String
If directory.Contains("/") Then
path = AdjustDir(directory) 'ensure that path starts with a slash
Else
path = directory
End If
' Set URI (formatted as ftp://host.xxx/path)
Dim URI As String = Me.Hostname & path
Dim response As FtpWebResponse
Dim DirExists As Boolean = False
Try
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(URI), FtpWebRequest)
request.Credentials = Me.GetCredentials
'Create Directory - if it exists WebException will be thrown
request.Method = WebRequestMethods.Ftp.MakeDirectory
'Delete Directory again - if above request did not throw an exception
response = DirectCast(request.GetResponse(), FtpWebResponse)
request = DirectCast(WebRequest.Create(URI), FtpWebRequest)
request.Credentials = Me.GetCredentials
request.Method = WebRequestMethods.Ftp.RemoveDirectory
response = DirectCast(request.GetResponse(), FtpWebResponse)
DirExists = False
Catch ex As WebException
DirExists = True
End Try
Return DirExists
End Function
WebRequestMethods.Ftp.MakeDirectory和WebRequestMethods.Ftp.RemoveDirectory是我用于此的方法。所有其他的解决方案都不适合我
希望能有所帮助这是我最好的选择。从父目录获取列表,并检查父目录是否具有正确的子名称
public void TryConnectFtp(string ftpPath)
{
string[] splited = ftpPath.Split('/');
StringBuilder stb = new StringBuilder();
for (int i = 0; i < splited.Length - 1; i++)
{
stb.Append(splited[i] +'/');
}
string parent = stb.ToString();
string child = splited.Last();
FtpWebRequest testConnect = (FtpWebRequest)WebRequest.Create(parent);
testConnect.Method = WebRequestMethods.Ftp.ListDirectory;
testConnect.Credentials = credentials;
using (FtpWebResponse resFtp = (FtpWebResponse)testConnect.GetResponse())
{
StreamReader reader = new StreamReader(resFtp.GetResponseStream());
string result = reader.ReadToEnd();
if (!result.Contains(child) ) throw new Exception("@@@");
resFtp.Close();
}
}
public void TryConnectFtp(字符串ftpPath)
{
string[]splited=ftpPath.Split('/');
StringBuilder stb=新的StringBuilder();
对于(int i=0;i
这将只返回CWD(当前工作目录)。无论您将什么附加到主机地址(例如:)中,它都将始终返回当前目录。换句话说,IsExists将永远不会是除true之外的任何内容。如果这是我做的唯一一件事(如上所述),那么在我的服务器上,它只会显示“257'/'是当前目录”。不是“257'/abcdir/”是当前目录。这是每个人都会想到的。这段代码是不可靠的:例如,如果你还没有写