using System.Net;using System.IO;using System.Net.Sockets; ファイルを転送のメソッド#region ファイルを転送のメソッド private static int BUFFER_SIZE = 512; //バッファのサイズ private Socket ClientSocket; //クライアント側のソケット オブジェクト private string RemoteHost = ""; //ホスト public string Host ...{ get ...{ return RemoteHost; } set ...{ RemoteHost = value; } } private int RemotePort = 21; //ポート public int Port ...{ get ...{ return RemotePort; } set ...{ RemotePort = value; } } private string RetMsg; //返りメッセージ private int RetMsgId; //返り値ID Encoding Ascii = Encoding.Default; //文字エンコーディング /**//// <summary> /// FTPを接続する /// </summary> /// <param name="Host">ホスト</param> /// <param name="Port">ポート</param> /// <param name="User">ユーザ</param> /// <param name="Pass">パスワード</param> /// <returns> /// 1 : 接続成功 /// 0 : 接続失敗 /// -110 : サービスが停止します /// </returns> public int ConnectFTP(string Host, int Port, string User, string Pass) ...{ try ...{ //毎週日曜日0:00-7:00はサービスが停止します DateTime dt = DateTime.Now; if ("Saturday".Equals(dt.DayOfWeek.ToString()) && dt.Hour >= 0 && dt.Hour <= 6) ...{ return 110; } //クライアント側のソケット オブジェクトを初期化する ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ep = new IPEndPoint(Dns.GetHostAddresses(Host)[0], Port); //FTPを接続する ClientSocket.Connect(ep); ReadMessage(); if (RetMsgId != 220) ...{ ClientSocket = null; return 0; } //ユーザとパスワードでFTPへログインする //ユーザを送信する SendCommand("USER " + User); if (!(RetMsgId == 331 || RetMsgId == 230)) ...{ //FTPの接続を閉じる DisconnectFTP(); return 0; } //パスワードを送信する SendCommand("PASS " + Pass); if (!(RetMsgId == 230 || RetMsgId == 202)) ...{ //FTPの接続を閉じる DisconnectFTP(); return 0; } return 1; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// FTPを接続する /// </summary> /// <param name="User">ユーザ</param> /// <param name="Pass">パスワード</param> /// <returns> /// 1 : 接続成功 /// 0 : 接続失敗 /// -110 : サービスが停止します /// </returns> public int ConnectFTP(string User, string Pass) ...{ int Ret = 0; //返り値 try ...{ //FTPを接続する Ret = ConnectFTP(RemoteHost, RemotePort, User, Pass); return Ret; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// FTPの接続を閉じる /// </summary> public void DisconnectFTP() ...{ try ...{ //クライアント側のソケット オブジェクトの判断 if (IsConnected()) ...{ //FTPを閉じる SendCommand("QUIT"); ClientSocket.Close(); } } catch (Exception ex) ...{ throw ex; } finally ...{ //ソケット オブジェクトを空にセットする ClientSocket = null; } } /**//// <summary> /// FTPへ接続を判断する /// </summary> /// <returns> /// true : FTPへ接続された /// false : FTPへ接続されない /// </returns> private bool IsConnected() ...{ try ...{ //クライアント側のソケット オブジェクトの判断 if (ClientSocket != null && ClientSocket.Connected == true) ...{ return true; } else ...{ return false; } } catch (Exception) ...{ ClientSocket = null; return false; } } /**//// <summary> /// ファイルをダウンロード /// </summary> /// <param name="SourceFileName">ソース ファイル</param> /// <param name="ObjectFileName">目標ファイル</param> /// <returns> /// 1 : ダウンロード成功 /// 0 : ダウンロード失敗 /// -100 : FTPを接続されない /// </returns> public int Download(string SourceFileName, string ObjectFileName) ...{ try ...{ //接続の判断 if (!IsConnected()) ...{ return -100; } int RetValue; //バイナリ タイプをセットする RetValue = SetType(false); if (RetValue == 0) ...{ return 0; } //目標ファイルの判断 if (ObjectFileName.Equals("")) ...{ ObjectFileName = SourceFileName; } if (!System.IO.File.Exists(ObjectFileName)) ...{ if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(ObjectFileName))) ...{ System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(ObjectFileName)); } Stream st = System.IO.File.Create(ObjectFileName); st.Close(); st.Dispose(); } //目標ファイルを作成する FileStream Output = new FileStream(ObjectFileName, FileMode.Open); Socket TempSocket = CreateDataSocket(); if (TempSocket == null) ...{ Output.Close(); Output.Dispose(); System.IO.File.Delete(ObjectFileName); return 0; } //ファイルを読みしのコマンドをFTPへ送信する SendCommand("RETR " + SourceFileName); if (!(RetMsgId == 150 || RetMsgId == 125)) ...{ Output.Close(); Output.Dispose(); System.IO.File.Delete(ObjectFileName); TempSocket.Close(); return 0; } //目標ファイルを書きます int Bytes; Byte[] Buffer = new Byte[BUFFER_SIZE]; while (true) ...{ Bytes = TempSocket.Receive(Buffer, Buffer.Length, 0); Output.Write(Buffer, 0, Bytes); if (Bytes <= 0) ...{ break; } } //目標ファイルを閉じる Output.Close(); Output.Dispose(); TempSocket.Close(); ReadMessage(); if (!(RetMsgId == 226 || RetMsgId == 250)) ...{ return 0; } return 1; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// ファイルをアップロードする /// </summary> /// <param name="SourceFileName">ソース ファイル</param> /// <returns> /// 1 : アップロード成功 /// 0 : アップロード失敗 /// -100 : FTPを接続されない /// </returns> public int Upload(string SourceFileName) ...{ try ...{ //接続の判断 if (!IsConnected()) ...{ return -100; } //ファイルをアクセスする用 ソケット オブジェクトを取得する Socket TempSocket = CreateDataSocket(); if (TempSocket == null) ...{ return 0; } //ファイルを格納しのコマンドをFTPへ送信する SendCommand("STOR " + Path.GetFileName(SourceFileName)); if (!(RetMsgId == 125 || RetMsgId == 150)) ...{ TempSocket.Close(); return 0; } //ソース ファイルがありませんの場合 if (System.IO.File.Exists(SourceFileName) == false) ...{ TempSocket.Close(); return 0; } //ソース ファイルを読みする FileStream Input = new FileStream(SourceFileName, FileMode.Open); int Bytes; Byte[] Buffer = new Byte[BUFFER_SIZE]; while ((Bytes = Input.Read(Buffer, 0, Buffer.Length)) > 0) ...{ TempSocket.Send(Buffer, Bytes, 0); } //ソース ファイルを閉じる Input.Close(); Input.Dispose(); TempSocket.Close(); ReadMessage(); if (!(RetMsgId == 226 || RetMsgId == 250)) ...{ return 0; } return 1; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// ファイルをアップロードする /// </summary> /// <param name="Input">開くしたファイル</param> /// <returns> /// 1 : アップロード成功 /// 0 : アップロード失敗 /// -100 : FTPを接続されない /// </returns> public int Upload(FileStream Input) ...{ try ...{ //接続の判断 if (!IsConnected()) ...{ Input.Close(); Input.Dispose(); return -100; } //ファイルをアクセスする用 ソケット オブジェクトを取得する Socket TempSocket = CreateDataSocket(); if (TempSocket == null) ...{ Input.Close(); Input.Dispose(); return 0; } //ソース ファイルを読みする int Bytes; Byte[] Buffer = new Byte[BUFFER_SIZE]; while ((Bytes = Input.Read(Buffer, 0, Buffer.Length)) > 0) ...{ TempSocket.Send(Buffer, Bytes, 0); } //ソース ファイルを閉じる Input.Close(); Input.Dispose(); TempSocket.Close(); ReadMessage(); if (!(RetMsgId == 226 || RetMsgId == 250)) ...{ return 0; } return 1; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// ファイル リストを取得する /// </summary> /// <param name="FileList">ファイル リスト</param> /// <returns> /// >0 : ファイルの個数 /// 0 : 取得失敗 /// -100 : FTPを接続されない /// </returns> public int GetFileList(ref string[] FileList) ...{ try ...{ //接続の判断 if (!IsConnected()) ...{ return -100; } //ファイルをアクセスする用 ソケット オブジェクトを取得する Socket TempSocket = CreateDataSocket(); if (TempSocket == null) ...{ return 0; } //リスト コマンドを送信する SendCommand("LIST "); if (!(RetMsgId == 150 || RetMsgId == 125)) ...{ return 0; } //ファイル リストを取得する RetMsg = ""; int Bytes; Byte[] Buffer = new Byte[BUFFER_SIZE]; while (true) ...{ Bytes = TempSocket.Receive(Buffer, Buffer.Length, 0); RetMsg += Ascii.GetString(Buffer, 0, Bytes); if (Bytes < Buffer.Length) ...{ break; } } //配列へファイル リストを格納する char[] Seperator = ...{ ' ' }; FileList = RetMsg.Split(Seperator); TempSocket.Close(); ReadMessage(); if (RetMsgId != 226) ...{ return 0; } //ファイルの個数を返却する return FileList.Length - 1; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// ファイル名 リストを取得する /// </summary> /// <param name="FileNameList">ファイル名 リスト</param> /// <returns> /// >0 : ファイル名の個数 /// 0 : 取得失敗 /// -100 : FTPを接続されない /// </returns> public int GetFileNameList(ref string[] FileNameList) ...{ //ファイル リストを取得する int Count = GetFileList(ref FileNameList); if (Count <= 0) ...{ return Count; } //ファイル リストによりファイル名 リストを取得する int Length; const int FILE_NAME_POS = 55; for (int i = 0; i < Count; i++) ...{ Length = FileNameList[i].Length; FileNameList[i] = FileNameList[i].Substring(FILE_NAME_POS, Length - FILE_NAME_POS - 1); } return 1; } /**//// <summary> /// ファイルが存在するかどうかを判断する /// </summary> /// <param name="FileNameList">ファイル名</param> /// <returns> /// 1 : 存在 /// 0 : 存在なし /// -100 : FTPを接続されない /// </returns> public int IsFileExists(string FileName) ...{ //ファイル名 リストを取得する string[] FileNameList = null; int Count = GetFileNameList(ref FileNameList); if (Count <= 0) ...{ return Count; } //ファイルが存在するかどうかを判断する int ExistFlg = 0; for (int i = 0; i < Count; i++) ...{ if (FileNameList[i] == FileName) ...{ ExistFlg = 1; break; } } return ExistFlg; } /**//// <summary> /// ファイルのサイズを取得する /// </summary> /// <param name="FileName">ファイル</param> /// <returns> /// -1 : 取得失敗 /// -100 : FTPを接続されない /// その他 : ファイルのサイズ /// </returns> public long GetFileSize(string FileName) ...{ try ...{ //接続の判断 if (!IsConnected()) ...{ return -100; } //SIZEコマンドを送信する、ファイルのサイズを取得する long Size = 0; SendCommand("SIZE " + FileName); if (RetMsgId == 213) ...{ Size = Int64.Parse(RetMsg.Substring(4)); } else ...{ return -1; } return Size; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// ファイル名を変更する /// </summary> /// <param name="OldFileName">古いファイル名</param> /// <param name="NewFileName">新しいファイル名</param> /// <returns> /// 1 : 変更成功 /// 0 : 変更失敗 /// -100 : FTPを接続されない /// </returns> public int RenameFile(string OldFileName, string NewFileName) ...{ try ...{ //接続の判断 if (!IsConnected()) ...{ return -100; } //変更されるファイルの古いファイル名を送信する SendCommand("RNFR " + OldFileName); if (RetMsgId != 350) ...{ return 0; } //変更されるファイルの新しいファイル名を送信する SendCommand("RNTO " + NewFileName); if (RetMsgId != 250) ...{ return 0; } return 1; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// ディレクトリを作成する /// </summary> /// <param name="DirectoryName">ディレクトリ名</param> /// <returns> /// 1 : 作成成功 /// 0 : 作成失敗 /// -100 : FTPを接続されない /// </returns> public int CreateDirectory(string DirectoryName) ...{ try ...{ //接続の判断 if (!IsConnected()) ...{ return -100; } //ディレクトリを作成する SendCommand("MKD " + DirectoryName); if (RetMsgId != 257) ...{ return 0; } return 1; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// ディレクトリを削除する /// </summary> /// <param name="DirectoryName">ディレクトリ名</param> /// <returns> /// 1 : 削除成功 /// 0 : 削除失敗 /// -100 : FTPを接続されない /// </returns> public int DeleteDirectory(string DirectoryName) ...{ try ...{ //接続の判断 if (!IsConnected()) ...{ return -100; } //ディレクトリを削除する SendCommand("RMD " + DirectoryName); if (RetMsgId != 250) ...{ return 0; } return 1; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// ファイルをアクセスする用 ソケット オブジェクトを作成する /// </summary> /// <returns> /// 作成したソケット オブジェクト /// </returns> private Socket CreateDataSocket() ...{ try ...{ //PASVコマンドを送信する SendCommand("PASV"); if (RetMsgId != 227) ...{ return null; } //IPアドレスとポートを取得する int Index1 = RetMsg.IndexOf('('); int Index2 = RetMsg.IndexOf(')'); string IpData = RetMsg.Substring(Index1 + 1, Index2 - Index1 - 1); string[] strParts; strParts = IpData.Split(','); string IpAddress = strParts[0] + "." + strParts[1] + "." + strParts[2] + "." + strParts[3]; int Port = (Int32.Parse(strParts[4]) << 8) + Int32.Parse(strParts[5]); //ファイルをアクセスする用 ソケット オブジェクトを作成する Socket TempSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); TempSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 5000); IPEndPoint ep = new IPEndPoint(Dns.GetHostAddresses(IpAddress)[0], Port); try ...{ TempSocket.Connect(ep); } catch (Exception) ...{ return null; } return TempSocket; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// FTPからメッセージを読みする /// </summary> private void ReadMessage() ...{ try ...{ //FTPからメッセージを読みする RetMsg = ""; ReadLine(); //メッセージIDを取得する RetMsgId = Int32.Parse(RetMsg.Substring(0, 3)); } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// FTPからメッセージの一つ行を読みする /// </summary> private string ReadLine() ...{ try ...{ //FTPからメッセージの一つ行を読みする int Bytes; Byte[] Buffer = new Byte[BUFFER_SIZE]; while (true) ...{ Bytes = ClientSocket.Receive(Buffer, Buffer.Length, 0); RetMsg += Ascii.GetString(Buffer, 0, Bytes); if (Bytes < Buffer.Length) ...{ break; } } //読みしたメッセージを取得する char[] Seperator = ...{ ' ' }; string[] Mess = RetMsg.Split(Seperator); if (RetMsg.Length > 2) ...{ RetMsg = Mess[Mess.Length - 2]; } else ...{ RetMsg = Mess[0]; } if (!RetMsg.Substring(3, 1).Equals(" ")) ...{ return ReadLine(); } //メッセージを返却する return RetMsg; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// コマンドを送信する /// </summary> /// <param name="Command">コマンド</param> private void SendCommand(String Command) ...{ try ...{ //コマンドを送信する Byte[] CommandBytes = Ascii.GetBytes((Command + " ").ToCharArray()); ClientSocket.Send(CommandBytes, CommandBytes.Length, 0); //FTPからメッセージを読みする ReadMessage(); return; } catch (Exception ex) ...{ throw ex; } } /**//// <summary> /// タイプをセットする /// </summary> /// <param name="Type">タイプ</param> /// <returns> /// 1 : セット成功 /// 0 : セット失敗 /// </returns> private int SetType(Boolean Type) ...{ try ...{ //タイプをセットする if (Type) ...{ //ASCIIタイプを送信する SendCommand("TYPE I"); } else ...{ //バイナリ タイプを送信する SendCommand("TYPE A"); } if (RetMsgId != 200) ...{ return 0; } return 1; } catch (Exception ex) ...{ throw ex; } } #endregion