【VB.NET】FluentFTP を使ってみた

【VB.NET】FTP:WebException (550) ファイルが使用できません」の最後に書いた通り、現在では System.Net に属する下記のクラスの使用が推奨されていません

  • FtpWebRequest
  • WebClient
  • WebRequest(HttpWebRequest)

で、VB.NET で FTP を行う手段として、FluentFTP を使ってみることにしたわけです(以前は System.Net.FtpClient として知られていたもの)。

インストール

Visual Studio の上部メニューから[ツール]>[NuGet パッケージ マネージャー]>[ソリューションの NuGet パッケージの管理]を選択。

[参照]を選択して検索ボックスに「fluentftp」と入力。FluentFTP が見つかったら選択して、右のペインでインストール先プロジェクトにチェックを入れ、[インストール]ボタンをクリック。

下図の確認ダイアログが表示されたら、[OK]ボタンをクリックするとインストールが開始します。

インストールの状況が出力ウィンドウに表示されます。

基本的な使い方

基本的な使い方は下記の通りです。(参考:GitHub - FluentFTP - Example Usage

' FTP クライアントの作成
Dim client As New FtpClient(var_Host)

'ログイン認証の指定をしない場合は、"anonymous" が使われる。
client.Credentials = New NetworkCredential(var_Username, var_Password)

' サーバーへの接続を開始
client.Connect()

' var_ServerTestDirectory1 フォルダのファイルとディレクトリのリストを取得。
' 変数 var_ServerTestDirectory1 の中身は "/DirectoryName" という形式で指定します。
For Each item As FtpListItem in client.GetListing(var_ServerTestDirectory1)

    Dim str As String = "■" & item.FullName & vbCrLf

    ' ファイルの場合
    If item.Type = FtpFileSystemObjectType.File Then
	
        ' ファイルサイズを取得
        Dim size As Long = client.GetFileSize(item.FullName)
        str &= "size:" & size.ToString & vbCrLf

    End If
	
    ' ファイルまたはフォルダの更新日時を取得
    Dim time As DateTime = client.GetModifiedTime(item.FullName)
    str &= "time:" & time.ToString & vbCrLf
	
    ' サーバー側のファイルのハッシュを計算(デフォルトのアルゴリズム)
    '   サーバーが Hash コマンドをサポートしている場合、
    '   FtpClient.HashAlgorithms フラグは FtpHashAlgorithm.NONE にならない。
    If client.HashAlgorithms <> FtpHashAlgorithm.NONE Then
        Dim hash As FtpHash = client.GetHash(item.FullName)
        str &= "hash:" & hash.Value & vbCrLf
    End If

    MsgBox(str)
Next

' ファイルのアップロード
MsgBox("Upload")
client.UploadFile("D:\temp\test.txt", var_ServerTestDirectory1 & "/Uploaded.txt")

' アップロードしたファイルのリネーム
MsgBox("Rename")
client.Rename(var_ServerTestDirectory1 & "/Uploaded.txt", var_ServerTestDirectory1 & "/Renamed.txt")

' 今度はダウンロード
MsgBox("Download")
client.DownloadFile("D:\temp\Downloaded.txt", var_ServerTestDirectory1 & "/Renamed.txt")

' サーバーのファイルを削除
MsgBox("Delete file")
client.DeleteFile(var_ServerTestDirectory1 & "/Renamed.txt")

' サーバーのディレクトリを再帰的に削除
MsgBox("Delete directory")
client.DeleteDirectory(var_ServerTestDirectory1 & "/")

' サーバーにディレクトリが存在するかチェック
MsgBox("Directory Exists")
MsgBox(client.DirectoryExists(var_ServerTestDirectory2).ToString)

' サーバーにファイルが存在するかチェック
MsgBox("File Exists")
MsgBox(client.FileExists(var_ServerTestDirectory2 & "/test2.txt").ToString)

' ファイルのアップロード。失敗した場合は3回まで試行する。
MsgBox("Upload - RetryAttempts")
client.RetryAttempts = 3
client.UploadFile("D:\temp\test.txt", var_ServerTestDirectory2 & "/Uploaded.txt", FtpExists.Overwrite, false, FtpVerify.Retry)

' 切断。またね!
MsgBox("Bye!")
client.Disconnect()

'破棄(切断も行う)。
client.Dispose 

 

更に詳細なサンプル(C#)が GitHub - FluentFTP に置かれています。

購読する
通知を受け取る対象
guest
0 Comments
Inline Feedbacks
View all comments