Hackztcx整理的FTP对象代码

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;

    }

/// <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

}
值得收藏~!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值