首页 新闻 论坛 群组 Blog 文档 下载 读书 Tag 网摘 搜索 .NET Java 游戏 视频 人才 外包 培训 数据库 书店 程序员
中国软件网
欢迎您:游客 | 登录 注册 帮助
  • 花了几个小时终于把ftp对象整理好了!!! [已结贴,结贴人:hackztx]
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    • hackztx
    • 等级:
    发表于:2008-06-11 21:50:44 楼主
    C# code
    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; }
    58  修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    • hackztx
    • 等级:
    发表于:2008-06-11 21:51:541楼 得分:0
    C# code
    /// <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 }
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    发表于:2008-06-11 21:52:542楼 得分:1
    收藏
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    • Navymk
    • 等级:
    发表于:2008-06-11 21:55:513楼 得分:1
    引用 2 楼 amandag 的回复:
    收藏

    学习socket
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    发表于:2008-06-12 08:48:484楼 得分:1
    强!支持!
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    发表于:2008-06-12 09:11:105楼 得分:1
    收藏学习!
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    • wangkun9999
    • 等级:
    发表于:2008-06-12 09:22:156楼 得分:1
    引用 2 楼 amandag 的回复:
    收藏
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    • nnnsu
    • 等级:
    发表于:2008-06-12 09:31:317楼 得分:1
    学习
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    发表于:2008-06-12 09:34:198楼 得分:1
    收藏,楼主辛苦了.
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    发表于:2008-06-12 09:40:029楼 得分:1
    收藏,楼主辛苦了.
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    发表于:2008-06-12 09:41:5410楼 得分:1
    Mark!
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    • hackztx
    • 等级:
    发表于:2008-06-12 09:49:2611楼 得分:0
    [code=c#]
    刚才又写了一个,如果把远程图片保存到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;
        }
    [/code]
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    发表于:2008-06-12 09:52:5612楼 得分:1
    顶 学习了o(∩_∩)o...
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天
    发表于:2008-06-12 09:53:4013楼 得分:1
    收藏, 顶
    修改 删除 举报 引用 回复
    进入用户个人空间
    加为好友
    发送私信
    在线聊天