Passiveモードやバイナリ転送モードでFTPサーバーにファイルを転送する (FtpWebRequest利用) - C#

FTPサーバに接続して、ファイルをアップロードします。アップロードのオプションとして、パッシブモードの切り替えやバイナリ転送モードへの切り替え、キープアライブ、タイムアウト時間の設定などができるコードを紹介します。
FTPでファイルをアップロードする場合には、WebClientクラスが利用できますが、より細かい設定ができるクラスとしてFtpWebRequestクラスが用意されています。

以下のコード例では、c:\data\にある mg.mp4ファイルを ftp.ipentec.com の/musicディレクトリに mg.mp4という名前でアップロードします。ファイル転送モードはバイナリ転送モードを使用します。

コード例

string upFile = "c:\data\mg.mp4";
Uri u = new Uri("ftp://ftp.ipentec.com/music/mg.mp4");

FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(u);
ftpReq.Credentials = new System.Net.NetworkCredential("penguin","password");

ftpReq.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftpReq.KeepAlive = false; //KeepAliveを無効
ftpReq.UseBinary = true;   //バイナリモードで転送
ftpReq.UsePassive = true;  //パッシブ接続にする
ftpReq.Timeout = 10000;

Stream reqStrm = ftpReq.GetRequestStream();
fileStream fs = new System.IO.FileStream(upFile, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[1024];
while (true) {
  int readSize = fs.Read(buffer, 0, buffer.Length);
  if (readSize == 0) break;
  reqStrm.Write(buffer, 0, readSize);
}
fs.Close();
reqStrm.Close();

FtpWebResponse ftpRes =(FtpWebResponse)ftpReq.GetResponse();
Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);
textBox1.Text+=string.Format("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);
ftpRes.Close();

コード例2

if (openFileDialog1.ShowDialog() == DialogResult.OK) {
  string upFile = openFileDialog1.FileName;
  Uri u = new Uri(textBox_FTPPath.Text+ Path.GetFileName(openFileDialog1.FileName));

  FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(u);
  ftpReq.Credentials
    = new System.Net.NetworkCredential(textBox_FTPUser.Text, textBox_FTPPass.Text);

  ftpReq.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
  ftpReq.KeepAlive = false; //KeepAliveを無効
  ftpReq.UseBinary = true;   //バイナリモードで転送
  ftpReq.UsePassive = true;  //パッシブ接続にする
  ftpReq.Timeout = 10000;

  Stream reqStrm = ftpReq.GetRequestStream();
  FileStream fs = new System.IO.FileStream(upFile, FileMode.Open, FileAccess.Read);
  byte[] buffer = new byte[1024];
  while (true) {
    int readSize = fs.Read(buffer, 0, buffer.Length);
    if (readSize == 0) break;
      reqStrm.Write(buffer, 0, readSize);
  }
  fs.Close();
  reqStrm.Close();

  FtpWebResponse ftpRes =(FtpWebResponse)ftpReq.GetResponse();
  Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);
  textBox1.Text+=string.Format("{0}: {1}", ftpRes.StatusCode,  ftpRes.StatusDescription);
        
  ftpRes.Close();
}
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2010-01-25
iPentec all rights reserverd.