C#通过FTP站点下载文件 C#下载FTP文件

在ftp站点下载文件:登录连接→下载 引用:using System.Net;

 using System.Net;
/// <summary>
 /// ftp站点文件下载
 /// </summary>
 /// <param name="serverPath"></param>
 /// <param name="localPath"></param>
 public static void FileDownload(string serverPath, string localPath)
 {

     if (!Directory.Exists(fileDerectory))
     {
         // 如果不存在,则创建路径
         Directory.CreateDirectory(fileDerectory);
     }
     string user = ConfigurationManager.AppSettings["User"].ToString();
     string password = ConfigurationManager.AppSettings["PassWord"].ToString();
     try
     {

         FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);
         request.Method = WebRequestMethods.Ftp.DownloadFile;
         request.Credentials = new NetworkCredential(user, password); // 替换为你的FTP登录信息
         using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
         using (Stream ftpStream = response.GetResponseStream())
         using (FileStream localFileStream = new FileStream(localPath, FileMode.Create))
         {
             byte[] buffer = new byte[4096]; // 你可以根据需要调整缓冲区大小
             int bytesRead;
             while ((bytesRead = ftpStream.Read(buffer, 0, buffer.Length)) != 0)
             {
                 localFileStream.Write(buffer, 0, bytesRead);
             }
         } // 在这里,ftpStream, localFileStream, 和 response 会被自动关闭,因为我们使用了 using 语句。
         TXTFileLogger.WriteLog(serverPath + "下载成功!");
     }
     catch (Exception ex)
     {
         TXTFileLogger.WriteLog(ex.Message);
         // 处理异常,例如显示错误消息或记录日志等。
     }
 }

调用示例:

首先,确保FTP服务器上的文件存在,这里事先搭建好一个FTP站点并新建一个TXT文件

调用代码:

 string serverPath = "ftp://192.168.100.48/1.txt";
 string loaclPath = "1.txt";
 FileDownload(serverPath, loaclPath);
 MessageBox.Show(File.ReadAllText(loaclPath));

执行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值