33

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を返します。誰かが私を正しい方向に向けることができますか?

4

11 に答える 11

20

基本的に、そのようなディレクトリを作成するときに受け取るエラーをトラップしました。

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;
        }  
    }
}
于 2010-05-07T21:43:45.490 に答える
16

私も同様の問題に悩まされていました。使っていた、

FtpWebRequest request = (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/」に変更しました。今、コードは私のために働いています。

ftp フォルダーの URI にフォワードスラッシュ (/) を追加して機能させる必要があると思います。

要求に応じて、完全なソリューションは次のようになります。

public bool DoesFtpDirectoryExist(string dirPath)
{
    try
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(dirPath);  
        request.Method = WebRequestMethods.Ftp.ListDirectory;  
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        return true;
     }
     catch(WebException ex)
     {
         return false;
     }
}

//Calling the method (note the forwardslash at the end of the path):
string ftpDirectory = "ftp://ftpserver.com/rootdir/test_if_exist_directory/";
bool dirExists = DoesFtpDirectoryExist(ftpDirectory);
于 2014-06-04T21:33:50.367 に答える
9

.NETでFTPにアクセスする通常の方法であるため、FtpWebRequestについてはすでにある程度理解していると思います。

ディレクトリを一覧表示して、エラーStatusCodeを確認することができます。

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.  
        }  
    }  
} 
于 2012-08-20T16:15:37.230 に答える
7

私はこの行に沿って何かを試してみます:

  • MLST <directory> FTP コマンド (RFC3659 で定義) を送信し、その出力を解析します。既存のディレクトリのディレクトリの詳細を含む有効な行を返す必要があります。

  • MLST コマンドを使用できない場合は、CWD コマンドを使用して、作業ディレクトリをテスト済みのディレクトリに変更してみてください。戻ることができるように、テスト済みのディレクトリに変更する前に、現在のパス (PWD コマンド) を確認することを忘れないでください。

  • 一部のサーバーでは、MDTM と SIZE コマンドの組み合わせを同様の目的で使用できますが、動作は非常に複雑で、この記事の範囲外です。

これは基本的に、現在のバージョンのRebex FTP コンポーネントの DirectoryExists メソッドが行うことです。次のコードは、その使用方法を示しています。

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();
于 2010-12-17T16:33:37.030 に答える
4

このコードを使用して、それがあなたの答えかもしれません。

 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);

別のライブラリを使用する理由-独自のロジックを作成します。

于 2011-07-20T10:44:58.103 に答える
2

確かなチェックを得るためにすべての方法を試しましたが、どちらの方法も正しく機能しWebRequestMethods.Ftp.PrintWorkingDirectoryませんでした。WebRequestMethods.Ftp.ListDirectoryサーバーに存在しないものを確認するときに失敗しftp://<website>/Logsましたが、存在すると言います。

そこで私が思いついた方法は、フォルダにアップロードしようとすることでした。ただし、1 つの「落とし穴」は、このスレッドLinux へのアップロードで読むことができるパス形式です。

ここにコードスニペットがあります

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; 
} 
于 2011-11-02T16:48:13.983 に答える
0

親ディレクトリに移動し、「ls」コマンドを実行して、結果を解析します。

于 2010-05-04T21:38:46.140 に答える
0

この@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"

その後、これは機能し始めます。

于 2010-09-24T17:04:37.423 に答える
-3

私にとってうまくいった唯一の方法は、ディレクトリ/パスを作成しようとする逆のロジックでした(既に存在する場合は例外がスローされます)。その場合は、後でもう一度削除します。それ以外の場合は、例外を使用して、ディレクトリ/パスが存在することを意味するフラグを設定します。私は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 は、これに使用したメソッドです。他のすべてのソリューションはうまくいきませんでした。

それが役に立てば幸い

于 2016-05-08T18:57:42.993 に答える
-5

その価値はありますが、EnterpriseDT の FTPコンポーネントを使用すると、FTP ライフがかなり楽になります。これは無料で、コマンドと応答を処理するため、頭痛の種から解放されます。素敵でシンプルなオブジェクトを操作するだけです。

于 2010-05-04T21:48:37.870 に答える