private string strHost, strPath, strUser, strPassword, strMessage;
    private int intPort, bytes;
    private Socket socket;
    private int intStatusNumber;
    private string strReply;
    Byte[] buffer = new Byte[1024];
    Encoding encoding = Encoding.Default;       #region 基本构造函数
    /// <summary>
    /// 构造函数(默认端口21)
    /// </summary>
    /// <param name="strHost">主机IP</param>
    /// <param name="strUser">账号</param>
    /// <param name="strPassword">密码</param>
    public FTP(string strHost, string strUser, string strPassword)  : this(strHost, 21, strUser, strPassword)
    {
    }
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="strHost">主机IP</param>
    /// <param name="intPort">端口号</param>
    /// <param name="strUser">账号</param>
    /// <param name="strPassword">密码</param>
    public FTP(string strHost, int intPort, string strUser, string strPassword)
    {
        this.strHost = strHost;
        this.strPath = ".";
        this.strUser = strUser;
        this.strPassword = strPassword;
        this.intPort = intPort;
    }    public void SetEncoding(Encoding encoding)
    {
        this.encoding = encoding;
    }
    public void SetEncoding(string strName)
    {
        this.encoding = Encoding.GetEncoding(strName);
    }
    public void SetEncoding(int encodingIndex)
    {
        this.encoding = Encoding.GetEncoding(encodingIndex);
    }
    public void Setbuffer(uint buff)
    {
        this.buffer = new byte[buff];
    }
    #endregion    /// <summary>
    /// 得到一个目录下的List
    /// </summary>
    /// <param name="strName">目录名</param>
    /// <returns></returns>
    public string[] GetFileList(string strName)
    {
        Socket sk = CreateSocket();
        SetCommand("NLST " + strName);
        if (!(intStatusNumber == 150 || intStatusNumber == 125))
        {
            return null;
        }
        strMessage = string.Empty;
        while (true)
        {
            int bytes = sk.Receive(buffer, buffer.Length, 0);
            strMessage += encoding.GetString(buffer, 0, bytes);
            if (bytes < buffer.Length)
            {
                break;
            }
        }
        string[] strFileNames = strMessage.Split(new char[] { '\n' });
        sk.Close();
        ChangeValue();
        if (intStatusNumber != 226)
        {
            throw new IOException(strReply.Substring(4));
        }
        return strFileNames;
    }    /// <summary>
    /// 得到文件大小
    /// </summary>
    /// <param name="fileName">文件路径</param>
    /// <returns>-1表示出现错误</returns>
    public int GetFileSize(string fileName)
    {
        try
        {
            SetCommand("SIZE " + fileName);
            int size = 0;
            if (intStatusNumber == 213)
            {
                size = int.Parse(strReply.Substring(4));
            }
            else
            {
                throw new IOException(strReply.Substring(4));
            }
            return size;
        }
        catch 
        {
            return -1;
        }
    }    /// <summary>
    /// 登陆到FTP服务器
    /// </summary>
    public bool Login()
    {
        bool blLogin = false;
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint ep = new IPEndPoint(IPAddress.Parse(strHost), intPort);
        try
        {
            socket.Connect(ep);
            ChangeValue();
            if (intStatusNumber != 220)
            {
                Close();
                throw new IOException(strReply.Substring(4));
            }
  
            SetCommand("USER " + strUser);            if (!(intStatusNumber == 331 || intStatusNumber == 230))
            {
                CleanUP();
                throw new IOException(strReply.Substring(4));
            }            if (intStatusNumber != 230)
            {
                SetCommand("PASS " + strPassword);
                if (!(intStatusNumber == 230 || intStatusNumber == 202))
                {
                    CleanUP();
                    throw new IOException(strReply.Substring(4));
                }
            }
            blLogin = true;
        }
        catch (Exception)
        {
            throw new IOException("Couldn't connect to remote server");
        }
        return blLogin;
    }
  
    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="strRemoteName">远程地址</param>
    /// <param name="strLocalName">保存本地路径</param>
    public bool DownLoadFile(string strRemoteName, string strLocalName)
    {
        bool bl = true;
        FileStream stream = null;
        Socket sk = null;
        try
        {
            if (!File.Exists(strLocalName))
            {
                Stream st = File.Create(strLocalName);
                st.Close();
            }
            stream = new FileStream(strLocalName, FileMode.Open);
            sk = CreateSocket();
            SetCommand("RETR " + strRemoteName);
            if (!(intStatusNumber == 150 || intStatusNumber == 125))
            {
                throw new IOException(strReply.Substring(4));
            }
            while (true)
            {
                bytes = sk.Receive(buffer, buffer.Length, 0);
                stream.Write(buffer, 0, bytes);
                if (bytes <= 0)
                {
                    break;
                }
            }
            ChangeValue();
            if (!(intStatusNumber == 226 || intStatusNumber == 250))
            {
                throw new IOException(strReply.Substring(4));
            }
        }
        catch
        {
            bl = false;
        }
        finally
        {
            if (sk != null)
            {
                sk.Close();
            }
            if (stream != null)
            {
                stream.Close();
            }
        }
        return bl;
    }    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <param name="strNewName">新的文件名如 abc
    /// 如果为空那么采用原来的文件名</param>
    public bool UPLoadFile(string fileName,string strNewName)
    {
        bool bl = true;
        Socket sk = CreateSocket();
        FileStream stream = null;
        try
        {
            if (strNewName.Length == 0)
            {
                SetCommand("STOR " + Path.GetFileName(fileName));
            }
            else
            {
                SetCommand("STOR " + strNewName + fileName.Substring(fileName.LastIndexOf(".")));
            }
            if (!(intStatusNumber == 125 || intStatusNumber == 150))
            {
                throw new IOException(strReply.Substring(4));
            }
             stream = new FileStream(fileName, FileMode.Open);
            while ((bytes = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                sk.Send(buffer, bytes, 0);
            }
            ChangeValue();
            if (!(intStatusNumber == 226 || intStatusNumber == 250))
            {
                throw new IOException(strReply.Substring(4));
            }
        }
        catch
        {
            bl = false;
        }
        finally
        {
            if (sk != null)
            {
                sk.Close();
            }
            if (stream != null)
            {
                stream.Close();
            }
        }        return bl;
    }

解决方案 »

  1.   

     /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName">传入文件地址</param>
        public bool RemoveFile(string fileName)
        {
            bool bl = true;
            try
            {
                SetCommand("DELE " + fileName);
                if (intStatusNumber != 250)
                {
                    throw new IOException(strReply.Substring(4));
                }
            }
            catch
            {
                bl = false;
            }
            return bl;
        }
        /// <summary>
        /// 重命名文件
        /// </summary>
        /// <param name="strName">文件地址</param>
        /// <param name="strNewName">新的文件名(如 abc)</param>
        public bool RenameFile(string strName, string strNewName)
        {
            bool bl = true;
            try
            {
                SetCommand("RNFR " + strName);
                if (intStatusNumber != 350)
                {
                    throw new IOException(strReply.Substring(4));
                }
                SetCommand("RNTO " + strNewName + strName.Substring(strName.LastIndexOf(".")));
                if (intStatusNumber != 250)
                {
                    throw new IOException(strReply.Substring(4));
                }
            }
            catch
            {
                bl = false;
            }
            return bl;
        }
        /// <summary>
        /// 新建一个目录
        /// </summary>
        /// <param name="strName">目录名</param>
        /// <returns></returns>
        public bool CreateDirectory(string strName)
        {
            bool bl = true;
            try
            {
                SetCommand("MKD " + strName);
                if (intStatusNumber != 257)
                {
                    throw new IOException(strReply.Substring(4));
                }
            }
            catch
            {
                bl = false;
            }
            return bl;
        }
        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="strFolderName">文件夹名</param>
        public bool RomoveDirectory(string strName)
        {
            bool bl = true;
            try
            {
                SetCommand("RMD " + strName);
                if (intStatusNumber != 250)
                {
                    throw new IOException(strReply.Substring(4));
                }
            }
            catch
            {
                bl = false;
            }
            return bl;
        }
        /// <summary>
        /// 更改当前目录
        /// </summary>
        /// <param name="dirName">输入目录</param>
        public bool AlterDirectory(string strName)
        {
            bool bl = true;
            try
            {
                SetCommand("CWD " + strName);
                if (intStatusNumber != 250)
                {
                    throw new IOException("no such directory");
                }
                this.strPath = strName;
            }
            catch
            {
                bl = false;
            }
            return bl;
        }
        #region 退出FTP连接
        public void Close()
        {
            if (socket != null)
            {
                SetCommand("QUIT");
            }
            CleanUP();
            Console.WriteLine("Closing...");
        }
        #endregion    #region 更改状态值 执行一个动作根据返回值判断是否出现异常
        private void ChangeValue()
        {
            strMessage = "";
            strReply = GetReceive();
            intStatusNumber = Int32.Parse(strReply.Substring(0, 3));
        }
        #endregion    #region 关闭通信
        private void CleanUP()
        {
            if (socket != null)
            {
                socket.Close();
                socket = null;
            }
        }
        #endregion    #region 执行一个动作得到服务器反馈信息
        private string GetReceive()
        {
            while (true)
            {
                bytes = socket.Receive(buffer, buffer.Length, 0);
                strMessage += encoding.GetString(buffer, 0, bytes);
                if (bytes < buffer.Length)
                {
                    break;
                }
            }
            string[] strMessages = strMessage.Split(new char[] { '\n' });
            if (strMessage.Length > 2)
            {
                strMessage = strMessages[strMessages.Length - 2];
            }
            else
            {
                strMessage = strMessages[0];
            }        if (!strMessage.Substring(3, 1).Equals(" "))
            {
                return GetReceive();
            }        return strMessage;
        }
        #endregion    #region 执行FTP命令
        private void SetCommand(String command)
        {
            Byte[] bytes = Encoding.Default.GetBytes((command + "\r\n").ToCharArray());
            socket.Send(bytes, bytes.Length, 0);
            ChangeValue();
        }
        #endregion    #region 建立一个Socket对象
        private Socket CreateSocket()
        {        SetCommand("PASV");
            if (intStatusNumber != 227)
            {
                throw new IOException(strReply.Substring(4));
            }
            int leftBracket = strReply.IndexOf('(');
            int rightBracket = strReply.IndexOf(')');
            string strIP = strReply.Substring(leftBracket + 1, rightBracket - leftBracket - 1);
            int[] parts = new int[6];
            int len = strIP.Length;
            int partCount = 0;
            string buf = "";
            for (int i = 0; i < len && partCount <= 6; i++)
            {
                char ch = Char.Parse(strIP.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);
                    }
                }
            }
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3]), (parts[4] << 8) + parts[5]);
            try
            {
                sock.Connect(ipep);
            }
            catch (Exception)
            {
                throw new IOException("Can't connect to remote server");
            }
            return sock;
        }
        #endregion
    }
      

  2.   


    刚才又写了一个,如果把远程图片保存到ftp服务器里
    源代码如下: private static Stream GetStream(string strLink)
        {
            HttpWebRequest request = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(strLink);
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1;.NET CLR 2.0.50727)";
                return request.GetResponse().GetResponseStream();
            }
            catch
            {
                request.Abort();
                return null;
            }
       
        }
      public bool UPLoadFile(string fileName,string strNewName)
        {
            bool bl = true;
            Socket sk = CreateSocket();
            Stream stream=null;
            try
            {
                if (strNewName.Length == 0)
                {
                    SetCommand("STOR " + Path.GetFileName(fileName));
                }
                else
                {
                    SetCommand("STOR " + strNewName + fileName.Substring(fileName.LastIndexOf(".")));
                }
                if (!(intStatusNumber == 125 || intStatusNumber == 150))
                {
                    throw new IOException(strReply.Substring(4));
                }
                if (fileName.ToLower().StartsWith("http"))
                {
                    stream = GetStream(fileName);
                }
                else
                {
                    stream = new FileStream(fileName, FileMode.Open);
                }
                while ((bytes = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    sk.Send(buffer, bytes, 0);
                }
                ChangeValue();
                if (!(intStatusNumber == 226 || intStatusNumber == 250))
                {
                    throw new IOException(strReply.Substring(4));
                }
            }
            catch
            {
                bl = false;
            }
            finally
            {
                if (sk != null)
                {
                    sk.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
            }        return bl;
        }
      

  3.   


    我靠...短消息(大部分是)收不到的.....你如果有什么话不方便说..请发送信息到我的email里面[email protected]
      

  4.   

    我以前是用FtpWebRequest的,楼主向你学习
      

  5.   

    还有一个问题,续传问题值得商讨(如果在WINFORM)
      

  6.   

    网上资料应该很多....我只是实现我的需求,到时候如果我要做到断点续传,可以就会研究!
    续传应该很简单..比如说一个文件2k我上传到1k死机了..然后我接着传就可以把前1k的数据给过滤掉,然后把后面的1k增补到已经写入1k的文件!
      

  7.   

    http://download.csdn.net/user/hackztx/刚刚上传
    要下载的朋友请稍等下!
      

  8.   

    恩,一直想研究下FTP,多谢楼主
      

  9.   


     private string strHost, strPath, strUser, strPassword, strMessage;
        private int intPort, bytes;
        private Socket socket;
        private int intStatusNumber;
        private string strReply;
        Byte[] buffer = new Byte[1024];
        Encoding encoding = Encoding.Default;
      

  10.   

    刚用了,在用DownLoadFile函数的时候会报错,因为socket是null的原因.得改进阿
      

  11.   

    FTP ftp = new FTP("59.34.131.56", "帐号", "密码");
            ftp.Login();
            ftp.DownLoadFile("aaa.gif","C:\\abc.gif");
      

  12.   

     and ...study and study...
      

  13.   

     and ... study and study...
      

  14.   

    楼主,
    UPLoadFile函数出错,
    进去就出不来了
    具体在
    ChangeValue();语句
    进入ChangeValue(),再进入ChangeValue()函数中strReply = GetReceive();语句中的GetReceive()函数
    在bytes = socket.Receive(buffer, buffer.Length, 0);这句上停住不动了我是菜鸟不知道为什么,楼主快来看看啊。
      

  15.   

    Microghost 夜半鬼你好!你mail是多少?
    我重新传一份给你!使用的是c#类库的对象!可以参考http://topic.csdn.net/u/20080615/11/a736ba3d-e420-432b-b54a-aafcff0957f1.html