#region 目录操作 /// <summary> /// 创建目录 /// </summary> /// <param name="strDirName">目录名</param> public void MkDir(string strDirName) { if(!bConnected) { Connect(); } SendCommand("MKD "+strDirName); if(iReplyCode != 257) { throw new IOException(strReply.Substring(4)); } }
/// <summary> /// 删除目录 /// </summary> /// <param name="strDirName">目录名</param> public void RmDir(string strDirName) { if(!bConnected) { Connect(); } SendCommand("RMD "+strDirName); if(iReplyCode != 250) { throw new IOException(strReply.Substring(4)); } }
/// <summary> /// 改变目录 /// </summary> /// <param name="strDirName">新的工作目录名</param> public void ChDir(string strDirName) { if(strDirName.Equals(".") || strDirName.Equals("")) { return; } if(!bConnected) { Connect(); } SendCommand("CWD "+strDirName); if(iReplyCode != 250) { throw new IOException(strReply.Substring(4)); } this.strRemotePath = strDirName; }
#endregion
/// <summary> /// 将一行应答字符串记录在strReply和strMsg /// 应答码记录在iReplyCode /// </summary> private void ReadReply() { strMsg = ""; strReply = ReadLine(); iReplyCode = Int32.Parse(strReply.Substring(0,3)); }
/// <summary> /// 建立进行数据连接的socket /// </summary> /// <returns>数据连接socket</returns> private Socket CreateDataSocket() { SendCommand("PASV"); if(iReplyCode != 227) { throw new IOException(strReply.Substring(4)); } int index1 = strReply.IndexOf('('); int index2 = strReply.IndexOf(')'); string ipData = strReply.Substring(index1+1,index2-index1-1); int[] parts = new int[6]; int len = ipData.Length; int partCount = 0; string buf=""; for (int i = 0; i < len && partCount <= 6; i++) { char ch = Char.Parse(ipData.Substring(i,1)); if (Char.IsDigit(ch)) buf+=ch; else if (ch != ',') { throw new IOException("Malformed PASV strReply: " + strReply); } if (ch == ',' || i+1 == len) { try { parts[partCount++] = Int32.Parse(buf); buf=""; } catch (Exception) { throw new IOException("Malformed PASV strReply: " + strReply); } } } string ipAddress = parts[0] + "."+ parts[1]+ "." + parts[2] + "." + parts[3]; int port = (parts[4] << 8) + parts[5]; Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipAddress), port); try { s.Connect(ep); } catch(Exception) { throw new IOException("Can't connect to remote server"); } return s; }
/// <summary> /// 关闭socket连接(用于登录以前) /// </summary> private void CloseSocketConnect() { if(socketControl!=null) { socketControl.Close(); socketControl = null; } bConnected = false; }
|