SSブログ

C#.NETでFTPダウンロードを実装する方法 [プログラミング]

C#.NETでFTPダウンロードを実装する方法について説明する。

ここで説明する内容は、前回のVB.NETでFTPダウンロードを実装する方法のC#.NET版である。
基本的な実装方法はVB.NETと同様なので詳しい説明は割愛する。

VB.NET版と異なる点は、FTPに関するコードの記述をクラス化(clsFtpクラス)しているということで、フォームに入力された内容をclsFtpクラスのプロパティに設定してからfncGetFileForFtpプロシージャを実行している。

以下がそのサンプルコード(抜粋)である。


------------------------------------------------------------

namespace TestFtp
{
    public partial class frmMain : Form
    {

        private void btnConnect_Click(object sender, EventArgs e)
        {
            //*****************************
            //接続ボタン押下時の処理
            //*****************************

            //Ftpクラスの生成
            clsFtp clsFtp = new clsFtp();
            //各種ユーザ入力情報の取得
            clsFtp.FireWallServer = txtFireWallServer.Text.Trim();
            clsFtp.FireWallUser = txtFireWallUser.Text.Trim();
            clsFtp.FireWallPassword = txtFireWallPassword.Text.Trim();
            clsFtp.HostProxy = txtHostProxy.Text.Trim();
            clsFtp.HostServer = txtHostServer.Text.Trim();
            clsFtp.HostUser = txtHostUser.Text.Trim();
            clsFtp.HostPassword = txtHostPassword.Text.Trim();
            clsFtp.HostPath = txtHostPath.Text.Trim();
            clsFtp.HostFile = txtHostFile.Text.Trim();
            clsFtp.ClientPath = txtClientPath.Text.Trim();
            clsFtp.ClientFile = txtClientFile.Text.Trim();
            //ログ出力先を設定
            clsFtp.Log = txtLog;

            //指定ファイルをFTPでサーバより取得
            clsPublic clsPublic = new clsPublic();
            if (clsFtp.fncGetFileForFtp() == false)
            {
                clsPublic.fncMessagePut("ファイルの取得に失敗しました。", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                clsPublic.fncMessagePut("ファイルの取得が完了しました。", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

 

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace TestFtp
{
    class clsFtp
    {
        private string strFireWallServer;
        private string strFireWallUser;
        private string strFireWallPassword;
        private string strHostProxy;
        private string strHostServer;
        private string strHostUser;
        private string strHostPassword;
        private string strHostPath;
        private string strHostFile;
        private string strClientPath;
        private string strClientFile;

        private TextBox txtLog;

        private Socket socClient;
        private System.IO.FileStream fsData;
        private Encoding encASC = new ASCIIEncoding();
        private Encoding encU8 = new UTF8Encoding();

        public string FireWallServer
        {
            get { return strFireWallServer; }
            set { strFireWallServer = value; }
        }
        public string FireWallUser
        {
            get { return strFireWallUser; }
            set { strFireWallUser = value; }
        }
        public string FireWallPassword
        {
            get { return strFireWallPassword; }
            set { strFireWallPassword = value; }
        }
        public string HostProxy
        {
            get { return strHostProxy; }
            set { strHostProxy = value; }
        }
        public string HostServer
        {
            get { return strHostServer; }
            set { strHostServer = value; }
        }
        public string HostUser
        {
            get { return strHostUser; }
            set { strHostUser = value; }
        }
        public string HostPassword
        {
            get { return strHostPassword; }
            set { strHostPassword = value; }
        }
        public string HostPath
        {
            get { return strHostPath; }
            set { strHostPath = value; }
        }
        public string HostFile
        {
            get { return strHostFile; }
            set { strHostFile = value; }
        }
        public string ClientPath
        {
            get { return strClientPath; }
            set { strClientPath = value; }
        }
        public string ClientFile
        {
            get { return strClientFile; }
            set { strClientFile = value; }
        }
        public TextBox Log
        {
            get { return txtLog; }
            set { txtLog = value; }
        }
        public Socket Client
        {
            get { return socClient; }
            set { socClient = value; }
        }

        public Boolean fncGetFileForFtp()
        {
            //*****************************
            //FTPで指定サーバより指定ファイルをダウンロード
            //
            //   戻り値         :   True:正常、False:異常
            //
            //*****************************

            Boolean blnReturn;
            Boolean blnConnect = false;

            try
            {
                txtLog.Clear();
                //ソケットオブジェクトの生成
                Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //FireWallサーバの接続先とポートを生成
                IPEndPoint iepFwIp = new IPEndPoint(Dns.GetHostEntry(FireWallServer).AddressList[0], 21);
                //FireWallサーバに接続
                Client.Connect(iepFwIp);
                //FireWallにログイン
                if (fncSendCommand("USER " + FireWallUser) == false)
                {
                    blnReturn = false;
                    goto Fin;
                }
                blnConnect = true;
                if (fncSendCommand("PASS " + FireWallPassword, FireWallPassword) == false)
                {
                    blnReturn = false;
                    goto Fin;
                }
                //サーバにログイン
                if (fncSendCommand("USER " + HostUser + "@" + HostServer + "@" + HostProxy) == false)
                {
                    blnReturn = false;
                    goto Fin;
                }
                if (fncSendCommand("PASS " + HostPassword, HostPassword) == false)
                {
                    blnReturn = false;
                    goto Fin;
                }
                //転送モードをASCIIに設定
                if (fncSendCommand("TYPE A") == false)
                {
                    blnReturn = false;
                    goto Fin;
                }
                //クライアントのIPアドレスと受信ポートを設定
                IPAddress ipaMyIp = Dns.GetHostAddresses(Dns.GetHostName())[1];
                TcpListener tlnData = new TcpListener(ipaMyIp, 0);
                tlnData.Start();
                int intMyPort = (int)((IPEndPoint)tlnData.LocalEndpoint).Port;

                //送受信ポートを設定
                if (fncSendCommand("PORT " + ipaMyIp.ToString().Replace(".", ",") + "," + (intMyPort / 256) + "," + (intMyPort % 256)) == false)
                {
                    blnReturn = false;
                    goto Fin;
                }
                //ダウンロードを要求するファイルを送信
                if (fncSendCommand("RETR " + HostPath + "/" + HostFile) == false)
                {
                    blnReturn = false;
                    goto Fin;
                }

                //ファイルをダウンロード
                Socket socData = tlnData.AcceptSocket();
                fsData = new System.IO.FileStream(System.IO.Path.Combine(ClientPath, ClientFile),
                    System.IO.FileMode.Create, System.IO.FileAccess.Write);
                byte[] bytBuffer = new byte[1023];
                DateTime datStart = DateTime.Now;
                while(true)
                {
                    int intSize=socData.Receive(bytBuffer);
                    if (intSize == 0)
                    { break; }
                    fsData.Write(bytBuffer, 0, intSize);
                }
                TimeSpan tsSpan = DateTime.Now - datStart;
                if (fncReceiveData() == false)
                {
                    blnReturn = false;
                    goto Fin;
                }
                string strMsg = "ダウンロードは正常に終了しました。 (" + Math.Ceiling(tsSpan.TotalSeconds) + "SEC. " +
                    (int)(fsData.Length / Math.Ceiling(tsSpan.TotalSeconds)) + "B/S)";
                subPutLog(strMsg);
                fsData.Close();
                socData.Close();

                blnReturn = true;
            }
            catch(Exception ex)
            {
                clsPublic clsPublic = new clsPublic();
                clsPublic.fncMessagePut(ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                blnReturn = false;
            }
            finally
            {
                if (blnConnect == true)
                {
                    if (fsData != null)
                    {
                        //出力ファイルを閉じる
                        fsData.Close();
                    }
                    //接続を閉じる
                    fncSendCommand("QUIT");
                    Client.Shutdown(SocketShutdown.Both);
                    Client.Close();
                }
                Client.Dispose();
                Client = null;
            }

            Fin:

            return blnReturn;
        }

        private Boolean fncReceiveData()
        {
            //*****************************
            //サーバから応答メッセージを取得
            //
            //   戻り値          :   True:正常、False:異常
            //
            //*****************************

            Boolean blnReturn;
            byte[] bytData = new byte[255];
            int intLen;
            string strData;

            try
            {
                while(Client.Available>0)
                {
                    //サーバからの応答を受信
                    intLen=Client.Receive(bytData);
                    //受信したメッセージのバイト列を文字列に変換
                    strData = encU8.GetString(bytData, 0, intLen);
                    subPutLog(strData);
                    System.Threading.Thread.Sleep(250);
                }

                blnReturn = true;

            }
            catch (Exception ex)
            {
                clsPublic clsPublic = new clsPublic();
                clsPublic.fncMessagePut(ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                blnReturn = false;
            }

            return blnReturn;
        }

        private Boolean fncSendCommand(string pCommand,string pPassword = "")
        {
            //*****************************
            //サーバにコマンドを送信
            //
            //   pCommand        :   送信コマンド文字列
            //   pPassword       :   パスワード文字列
            //
            //   戻り値          :   True:正常、False:異常
            //
            //*****************************

            Boolean blnReturn;

            try
            {
                //ログを出力
                pCommand = pCommand + "\r\n";
                subPutLog(">" + pCommand, pPassword);
                //送信するコマンドをASCIIのバイト列に変換
                byte[] bytCommand = encASC.GetBytes(pCommand);

                //コマンドを送信
                Client.Send(bytCommand, bytCommand.Length, SocketFlags.None);
                System.Threading.Thread.Sleep(250);

                //サーバからの応答を受信
                if (fncReceiveData() == false)
                {
                    blnReturn = false;
                }
                else
                {
                    blnReturn = true;
                }
            }
            catch(Exception ex)
            {
                clsPublic clsPublic = new clsPublic();
                clsPublic.fncMessagePut(ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                blnReturn = false;
            }

            return blnReturn;
        }

        private void subPutLog(string pMsg,string pPassword = "")
        {
            //*****************************
            //ログを出力
            //
            //   pMsg            :   メッセージ文字列
            //   pPassword       :   パスワード文字列
            //
            //*****************************

            if (txtLog.Text != "" && txtLog.Text.Substring(txtLog.TextLength - 2) != "\r\n")
            {
                txtLog.AppendText("\r\n");
            }
            if (pPassword != string.Empty)
            {
                pMsg=pMsg.Replace(pPassword,"[" + new string('X',pPassword.Length) + "]");
            }
            txtLog.AppendText(pMsg);
            Application.DoEvents();
        }
    }
}

------------------------------------------------------------

 


タグ:C#.NET FTP Socket
nice!(0)  コメント(0)  トラックバック(0) 

nice! 0

コメント 0

コメントを書く

お名前:
URL:
コメント:
画像認証:
下の画像に表示されている文字を入力してください。

トラックバック 0

この広告は前回の更新から一定期間経過したブログに表示されています。更新すると自動で解除されます。