c# 使用FtpWebRequest,FtpWebResponse ,Stream 实现获取文件列表及下载

public class FtpHelper
	{
		private FtpWebRequest ftpRequest = null;
		private FtpWebResponse ftpResponse = null;
		private Stream ftpStream = null;

		/// <summary>
		/// 直接传文件名获取信息
		/// </summary>
		/// <param name="userId">ftp userid</param>
		/// <param name="pwd">ftp password</param>
		/// <param name="ftpIP">ftp ip</param>
		/// <returns></returns>
		public string[] GetFtpFileName(string userId, string pwd, string ftpIP,string filename)
		{
			string[] downloadFiles;
			StringBuilder result = new StringBuilder();
			try
			{
				ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/"+ filename);
				ftpRequest.Credentials = new NetworkCredential(userId, pwd);
				ftpRequest.UseBinary = true;
				ftpRequest.UsePassive = true;
				ftpRequest.KeepAlive = true;
				ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
				ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
				ftpStream = ftpResponse.GetResponseStream();
				StreamReader ftpReader = new StreamReader(ftpStream);
				string line = ftpReader.ReadLine();
				while (line != null)
				{
					result.Append(line);
					result.Append("\n");
					line = ftpReader.ReadLine();
				}
				result.Remove(result.ToString().LastIndexOf('\n'), 1);
			
				ftpReader.Close();
				ftpStream.Close();
				ftpResponse.Close();
				ftpRequest = null;
				return result.ToString().Split('\n');

			}
			catch (Exception ex)
			{
				downloadFiles = null;
				return downloadFiles;
			}
		}
//直接连接好账号密码 地址遍历文件夹下所有文件信息
 public string[] GetFtpFileName(string userId, string pwd, string ftpIP)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            try
            {
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/");
                ftpRequest.Credentials = new NetworkCredential(userId, pwd);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpStream = ftpResponse.GetResponseStream();
                StreamReader ftpReader = new StreamReader(ftpStream);
                string line = ftpReader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = ftpReader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
            
                ftpReader.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
       
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                downloadFiles = null;
                return downloadFiles;
            }
        }
																											
        /// <summary>
        ///从ftp服务器上下载文件的功能
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pwd"></param>
        /// <param name="ftpUrl">ftp地址</param>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
		public void DownloadFtpFile(string userId, string pwd, string ftpUrl, string filePath, string fileName)
		{
			FtpWebRequest reqFTP=null;
			FtpWebResponse response = null;
      try
			{
				String onlyFileName = Path.GetFileName(fileName);

				string downFileName = filePath + "\\" + onlyFileName;
				string url = "ftp://" + ftpUrl + "/" + fileName;
				if (File.Exists(downFileName))
				{
					SearchDataClass.DeleteDir(downFileName);
				}

				FileStream outputStream = new FileStream(downFileName, FileMode.Create);

				reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
				reqFTP.Credentials = new NetworkCredential(userId, pwd);
				reqFTP.UseBinary = true;
				reqFTP.UsePassive = true;
				reqFTP.KeepAlive = true;
				reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
				response = (FtpWebResponse)reqFTP.GetResponse();

			
				Stream ftpStream = response.GetResponseStream();
				long cl = response.ContentLength;
				int bufferSize = 2048;
				int readCount;
				byte[] buffer = new byte[bufferSize];
				readCount = ftpStream.Read(buffer, 0, bufferSize);
				while (readCount > 0)
				{
					outputStream.Write(buffer, 0, readCount);
					readCount = ftpStream.Read(buffer, 0, bufferSize);
				}
				ftpStream.Close();
				outputStream.Close();
				response.Close();


			}
			catch (Exception ex)
			{
				throw ex;
			}
		} 
	}


使用方法:

	FtpHelper ftp = new model.FtpHelper();

            var tvname = drpTvName.SelectedItem.Text + ".xml";

            string[] getXmlList = ftp.GetFtpFileName("test", "123456", "ftp://xx.xx.x.139/", tvname);//直接传文件名

            string[] getXmlList = ftp.GetFtpFileName("test", "123456", "ftp://xx.xx.x.139/");
            for (var i = 0; i < getXmlList.Length; i++)
            {
                ftp.DownloadFtpFile("test", "123456", "xx.x.140.x", Server.MapPath("UpLoadImg/TvXML"), getXmlList[i].ToString());
                var path = Server.MapPath("UpLoadImg\\ChannelTvXML\\") + getXmlList[i].ToString();//可存放到数据库中
            }


其他参考文章:

http://blog.csdn.net/csethcrm/article/details/8139744

http://blog.csdn.net/wc871231/article/details/7418675

http://www.c-sharpcorner.com/uploadfile/f2e803/compression-of-xml-file-ftp-upload-and-sql-server-sqlbulkinsert/

http://zhidao.baidu.com/link?url=d9WCZNp8JZ74R3roPnTpDVsXqx8bmDftCrp_IKB-P8rzkFDqeaPpPoO3K_v0RRL2U6MVTzm_nSnMlgVQ35gccq

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值