.NET 对FTP上传和下载的编程

 class Zhaopin_FTP
    {
        //FTP服务器
        public string m_ftpServerIP = ConfigurationSettings.AppSettings["Z_FTPSERVERIP"];
        //FTP远程登录帐号
        public string m_ftpUserID = ConfigurationSettings.AppSettings["Z_FTPUSERID"];
        //FTP远程登录口令
        public string m_ftpPassword = ConfigurationSettings.AppSettings["Z_FTPPASSWORD"];








        //FTP默认以21号端口进行连接
        //FTP服务器响应码




        //创建一个FtpWebRequest对象,指向ftp服务器的Uri
        //设置ftp的执行方法(上传,下载等)
        //给FtpWebRequest对象设置属性(是否使用二进制传输等)
        //设置登录验证(用户名,密码)
        //执行请求
        //接收相应流
        //如果没有打开的流,则关闭ftp请求


        //UseBinary 文件的传输类型 Binary,ASCII
        //Credentials 指定登录ftp服务器的用户名和密码
        //Method 指定当前请求是什么命令(upload,download,filelist等),定义在结构体WebRequestMethods.Ftp中






        /// <summary>
        /// 获取目录结构
        /// </summary>
        /// <returns></returns>
        public string[] GetDirectoryList()
        {
            StringBuilder result = new StringBuilder();
            string[] DirectoryList;
            FtpWebRequest reqFTP;


            try
            {
                string strPath = "ftp://" + m_ftpServerIP + "/Resume/";


                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strPath));
                reqFTP.UseBinary = true;
                reqFTP.KeepAlive = false;
                reqFTP.Credentials = new NetworkCredential(m_ftpUserID, m_ftpPassword);
                //reqFTP.Timeout = 240000;


                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;


                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);


                string DataString = reader.ReadToEnd();
                string dirName = string.Empty;


                string[] dataRecords = DataString.Replace("\r", "").Split('\n');
                foreach (string oneRecord in dataRecords)
                {
                    if (oneRecord != "" && oneRecord != null)
                    {
                        if (oneRecord.Substring(0, 3).ToUpper().ToString().Trim() == "DRW")
                        {
                            //为目录
                            string[] strParams = oneRecord.Split(new char[] { ' ' });
                            if (strParams.Length > 0)
                            {
                                dirName = strParams[strParams.Length - 1];
                            }
                            if (dirName != "" && dirName != "." && dirName != "..")
                            {
                                result.Append(dirName);
                                result.Append("\n");
                            }
                        }
                    }
                }
                result.Remove(result.ToString().LastIndexOf('\n'), 1);


                reader.Close();
                response.Close();
                
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                Logger.WriteLog("获取目录时出现异常 "+ex.Message);
                DirectoryList = null;
                return DirectoryList;
            }
        }




        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string[] GetFileList(string path)
        {
            string[] FileList;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            
            try
            {
                string strPath = "ftp://" + m_ftpServerIP + "/Resume/" + path;
                //reqFTP.Timeout = 240000;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strPath));
                reqFTP.KeepAlive = false;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(m_ftpUserID, m_ftpPassword);


                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;


                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());


                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                Logger.WriteLog("获取文件列表时出现异常 " + ex.Message);
                FileList = null;
                return FileList;
            }
        }




        /// <summary>
        /// 下载XML文件
        /// </summary>
        /// <param name="ResumeDate"></param>
        /// <param name="ResumeName"></param>
        public void Download(string ResumeDate, string ResumeName)
        {
            FileStream fs = null;
            Stream ftpStream = null;
            FtpWebRequest reqFTP;
            
            try
            {
                string strPath = "ftp://" + m_ftpServerIP + "/Resume/"+ResumeDate+"/"+ResumeName;
                //reqFTP.Timeout = 240000;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strPath));
                reqFTP.KeepAlive = false;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(m_ftpUserID, m_ftpPassword);


                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;


                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                ftpStream = response.GetResponseStream();




                string strLocalFileName = GlobalVar.LocalResumePath + ResumeDate + "/" + ResumeName;
                if (File.Exists(strLocalFileName))     //如果文件存在, 将只读 打开和重写本地文件
                {


                }
                else
                {
                    fs = File.Create(strLocalFileName);
                }


                if (fs != null)
                {
                    int _buffer = 65536;
                    byte[] buffer = new byte[_buffer];
                    int size = 0;
                    while ((size = ftpStream.Read(buffer, 0, _buffer)) > 0)
                    {
                        fs.Write(buffer, 0, size);
                    }
                    fs.Flush();
                    fs.Close();
                    ftpStream.Close();
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog("下载XML文件出现异常 " + ex.Message);
                return;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
                if (ftpStream != null)
                    ftpStream.Close();
            }
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="FileName"></param>
        public void Upload(string FileName)
        {
            FileInfo fileInfo = new FileInfo(FileName);


            FtpWebRequest reqFTP;
            FileStream fs = null;
            Stream ftpStream = null;
            try
            {


                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + m_ftpServerIP + "/Position/" + fileInfo.Name));
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                reqFTP.KeepAlive = false;


                //reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(m_ftpUserID, m_ftpPassword);


                reqFTP.ContentLength = fileInfo.Length;
                int buffLength = int.Parse(fileInfo.Length.ToString());
                byte[] buf = new byte[buffLength];
                int contentLen;
                fs = fileInfo.OpenRead();


                try
                {
                    ftpStream = reqFTP.GetRequestStream();
                    contentLen = fs.Read(buf, 0, buffLength);
                    while (contentLen != 0)
                    {
                        ftpStream.Write(buf, 0, contentLen);
                        contentLen = fs.Read(buf, 0, buffLength);


                    }
                    ftpStream.Close();
                    fs.Close();
                }
                catch (Exception ex)
                {
                    Logger.WriteLog("Upload方法上传职位XML文件失败! " + ex.Message);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog("Upload方法上传职位XML文件失败! " + ex.Message);
            }
            finally
            {
                if (fs != null)
                    fs.Close();
                if (ftpStream != null)
                    ftpStream.Close();
            }
        }  
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值