打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
[转]C# FTP上传文件及文件夹至服务器代码
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.IO;  
  8. using System.Net;  
  9. using System.Globalization;  
  10. using System.Text;  
  11. using System.Net;  
  12.   
  13. namespace FTPwebsite  
  14. {  
  15.     public partial class test3 : System.Web.UI.Page  
  16.     {  
  17.         protected void Page_Load(object sender, EventArgs e)  
  18.         {  
  19.   
  20.         }  
  21.         private string ftpServerIP = "192.168.1.1";//服务器ip  
  22.         private string ftpUserID = "admin";//用户名  
  23.         private string ftpPassword = "123456";//密码  
  24.  
  25.         #region 上传文件  
  26.   
  27.         /// <summary>  
  28.         /// 上传文件  
  29.         /// </summary>  
  30.         /// <param name="localFile">要上传到FTP服务器的本地文件</param>  
  31.         /// <param name="ftpPath">FTP地址</param>  
  32.         public void UpLoadFile(string localFile, string ftpPath)  
  33.         {  
  34.             if (!File.Exists(localFile))  
  35.             {  
  36.                 Response.Write("文件:“" + localFile + "” 不存在!");  
  37.                 return;  
  38.             }  
  39.             FileInfo fileInf = new FileInfo(localFile);  
  40.             FtpWebRequest reqFTP;  
  41.   
  42.             reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpPath);// 根据uri创建FtpWebRequest对象   
  43.             reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);// ftp用户名和密码  
  44.             reqFTP.KeepAlive = false;// 默认为true,连接不会被关闭 // 在一个命令之后被执行  
  45.             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;// 指定执行什么命令  
  46.             reqFTP.UseBinary = true;// 指定数据传输类型  
  47.             reqFTP.ContentLength = fileInf.Length;// 上传文件时通知服务器文件的大小  
  48.             int buffLength = 2048;// 缓冲大小设置为2kb  
  49.             byte[] buff = new byte[buffLength];  
  50.             int contentLen;  
  51.   
  52.             // 打开一个文件流 (System.IO.FileStream) 去读上传的文件  
  53.             FileStream fs = fileInf.OpenRead();  
  54.             try  
  55.             {  
  56.                 Stream strm = reqFTP.GetRequestStream();// 把上传的文件写入流  
  57.                 contentLen = fs.Read(buff, 0, buffLength);// 每次读文件流的2kb  
  58.   
  59.                 while (contentLen != 0)// 流内容没有结束  
  60.                 {  
  61.                     // 把内容从file stream 写入 upload stream  
  62.                     strm.Write(buff, 0, contentLen);  
  63.                     contentLen = fs.Read(buff, 0, buffLength);  
  64.                 }  
  65.                 // 关闭两个流  
  66.                 strm.Close();  
  67.                 fs.Close();  
  68.                 Response.Write("文件【" + ftpPath + "/" + fileInf.Name + "】上传成功!<br/>");  
  69.             }  
  70.             catch (Exception ex)  
  71.             {  
  72.                 Response.Write("上传文件【" + ftpPath+"/"+fileInf.Name + "】时,发生错误:" + ex.Message + "<br/>");  
  73.             }  
  74.         }  
  75.  
  76.         #endregion  
  77.  
  78.         #region 上传文件夹  
  79.   
  80.         /// <summary>  
  81.         /// 上传整个目录  
  82.         /// </summary>  
  83.         /// <param name="localDir">要上传的目录的上一级目录</param>  
  84.         /// <param name="ftpPath">FTP路径</param>  
  85.         /// <param name="dirName">要上传的目录名</param>  
  86.         /// <param name="ftpUser">FTP用户名(匿名为空)</param>  
  87.         /// <param name="ftpPassword">FTP登录密码(匿名为空)</param>  
  88.         public void UploadDirectory(string localDir, string ftpPath, string dirName)  
  89.         {  
  90.             string dir = localDir +dirName+ @"\"//获取当前目录(父目录在目录名)  
  91.             //检测本地目录是否存在  
  92.             if (!Directory.Exists(dir))  
  93.             {  
  94.                 Response.Write("本地目录:“" + dir + "” 不存在!<br/>");  
  95.                 return;  
  96.             }  
  97.             //检测FTP的目录路径是否存在  
  98.             if (!CheckDirectoryExist(ftpPath, dirName))  
  99.             {  
  100.                 MakeDir(ftpPath, dirName);//不存在,则创建此文件夹  
  101.             }  
  102.             List<List<string>> infos = GetDirDetails(dir); //获取当前目录下的所有文件和文件夹  
  103.   
  104.             //先上传文件  
  105.             //Response.Write(dir + "下的文件数:" + infos[0].Count.ToString() + "<br/>");  
  106.             for (int i = 0; i < infos[0].Count; i++)  
  107.             {  
  108.                 Console.WriteLine(infos[0][i]);  
  109.                 UpLoadFile(dir + infos[0][i], ftpPath + dirName + @"/" + infos[0][i]);  
  110.             }  
  111.             //再处理文件夹  
  112.             //Response.Write(dir + "下的目录数:" + infos[1].Count.ToString() + "<br/>");  
  113.             for (int i = 0; i < infos[1].Count; i++)  
  114.             {  
  115.                 UploadDirectory(dir, ftpPath + dirName + @"/", infos[1][i]);  
  116.                 //Response.Write("文件夹【" + dirName + "】上传成功!<br/>");  
  117.             }  
  118.         }  
  119.   
  120.         /// <summary>  
  121.         /// 判断ftp服务器上该目录是否存在  
  122.         /// </summary>  
  123.         /// <param name="ftpPath">FTP路径目录</param>  
  124.         /// <param name="dirName">目录上的文件夹名称</param>  
  125.         /// <returns></returns>  
  126.         private bool CheckDirectoryExist(string ftpPath, string dirName)  
  127.         {  
  128.             bool flag = true;  
  129.             try  
  130.             {  
  131.                 //实例化FTP连接  
  132.                 FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpPath + dirName);  
  133.                 ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);  
  134.                 ftp.Method = WebRequestMethods.Ftp.ListDirectory;  
  135.                 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();  
  136.                 response.Close();  
  137.             }  
  138.             catch (Exception)  
  139.             {  
  140.                 flag = false;  
  141.             }  
  142.             return flag;  
  143.         }  
  144.   
  145.         /// <summary>  
  146.         /// 创建文件夹    
  147.         /// </summary>    
  148.         /// <param name="ftpPath">FTP路径</param>    
  149.         /// <param name="dirName">创建文件夹名称</param>    
  150.         public void MakeDir(string ftpPath, string dirName)  
  151.         {  
  152.   
  153.             FtpWebRequest reqFTP;  
  154.             try  
  155.             {  
  156.                 string ui = (ftpPath + dirName).Trim();  
  157.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(ui);  
  158.                 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;  
  159.                 reqFTP.UseBinary = true;  
  160.                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);  
  161.                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();  
  162.                 Stream ftpStream = response.GetResponseStream();  
  163.                 ftpStream.Close();  
  164.                 response.Close();  
  165.                 Response.Write("文件夹【" + dirName + "】创建成功!<br/>");  
  166.             }  
  167.   
  168.             catch (Exception ex)  
  169.             {  
  170.                 Response.Write("新建文件夹【" + dirName+"】时,发生错误:" + ex.Message);  
  171.             }  
  172.   
  173.         }  
  174.   
  175.         /// <summary>  
  176.         /// 获取目录下的详细信息  
  177.         /// </summary>  
  178.         /// <param name="localDir">本机目录</param>  
  179.         /// <returns></returns>  
  180.         private List<List<string>> GetDirDetails(string localDir)  
  181.         {  
  182.             List<List<string>> infos = new List<List<string>>();  
  183.             try  
  184.             {  
  185.                 infos.Add(Directory.GetFiles(localDir).ToList()); //获取当前目录的文件  
  186.   
  187.                 infos.Add(Directory.GetDirectories(localDir).ToList()); //获取当前目录的目录  
  188.   
  189.                 for (int i = 0; i < infos[0].Count; i++)  
  190.                 {  
  191.                     int index = infos[0][i].LastIndexOf(@"\");  
  192.                     infos[0][i] = infos[0][i].Substring(index + 1);  
  193.                 }  
  194.                 for (int i = 0; i < infos[1].Count; i++)  
  195.                 {  
  196.                     int index = infos[1][i].LastIndexOf(@"\");  
  197.                     infos[1][i] = infos[1][i].Substring(index + 1);  
  198.                 }  
  199.             }  
  200.             catch (Exception ex)  
  201.             {  
  202.                 ex.ToString();  
  203.             }  
  204.             return infos;  
  205.         }  
  206.  
  207.         #endregion  
  208.   
  209.         protected void Button1_Click(object sender, EventArgs e)  
  210.         {  
  211.             //FTP地址  
  212.             string ftpPath = "ftp://192.168.1.1/";  
  213.             //本机要上传的目录的父目录  
  214.             string localPath = "E:\\发布\\";  
  215.             //要上传的目录名  
  216.             string fileName = "test1";  
  217.   
  218.             FileInfo fi = new FileInfo(localPath);  
  219.             //判断上传文件是文件还是文件夹  
  220.             if ((fi.Attributes & FileAttributes.Directory) != 0)  
  221.             {  
  222.                 //dir 如果是文件夹,则调用[上传文件夹]方法  
  223.                 UploadDirectory(localPath, ftpPath, fileName);  
  224.             }  
  225.             else  
  226.             {  
  227.                 //file 如果是文件,则调用[上传文件]方法  
  228.                 UpLoadFile(localPath + fileName, ftpPath);  
  229.             }   
  230.               
  231.         }  
  232.     }  
  233. }  
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C# FTP上传、下载、删除
【C#】工具类-FTP操作封装类FTPHelper
C#如何操控FTP
C# winform 如何上传RAR文件到FTP服务器! 跪求!! - .net常见问题 ...
.net 2.0(c#)下简单的FTP应用程序
C# FTP操作工具
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服