架构师_程序员_码农网

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

搜索
查看: 23233|回复: 0

[资料] c# ftp上传帮助类

[复制链接]
发表于 2016-10-16 20:13:56 | 显示全部楼层 |阅读模式
QQ截图20161016201801.jpg

上传中文名称,会乱码,至今没有解决方法。。。

  1. public class FtpLib
  2.     {
  3.         string ftpServerIP;
  4.         string ftpServerPort;
  5.         string ftpRemotePath;
  6.         string ftpUserID;
  7.         string ftpPassword;
  8.         string ftpURI;

  9.         /// <summary>
  10.         /// 连接FTP
  11.         /// </summary>
  12.         /// <param name="FtpServerIP">FTP连接地址</param>
  13.         /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
  14.         /// <param name="FtpUserID">用户名</param>
  15.         /// <param name="FtpPassword">密码</param>
  16.         public FtpLib(string FtpServerIP, string FtpServerPort, string FtpRemotePath, string FtpUserID, string FtpPassword)
  17.         {
  18.             ftpServerIP = FtpServerIP;
  19.             ftpRemotePath = FtpRemotePath;
  20.             ftpUserID = FtpUserID;
  21.             ftpPassword = FtpPassword;
  22.             ftpServerPort = FtpServerPort;
  23.             ftpURI = "ftp://" + ftpServerIP + ":" + ftpServerPort + "/";
  24.             if (!string.IsNullOrEmpty(ftpRemotePath))
  25.             {
  26.                 ftpURI = ftpURI + ftpRemotePath + "/";
  27.             }
  28.         }

  29.         /// <summary>
  30.         /// 上传
  31.         /// </summary>
  32.         /// <param name="filename"></param>
  33.         public void Upload(string filename)
  34.         {
  35.             FileInfo fileInf = new FileInfo(filename);
  36.             //string uri = ftpURI + HttpUtility.UrlEncode(fileInf.Name, Encoding.UTF8);
  37.             string uri = ftpURI + fileInf.Name;
  38.             FtpWebRequest reqFTP;

  39.             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  40.             reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  41.             reqFTP.KeepAlive = false;
  42.             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
  43.             reqFTP.UseBinary = true;
  44.             reqFTP.ContentLength = fileInf.Length;
  45.             int buffLength = 2048;
  46.             byte[] buff = new byte[buffLength];
  47.             int contentLen;
  48.             FileStream fs = fileInf.OpenRead();
  49.             try
  50.             {
  51.                 Stream strm = reqFTP.GetRequestStream();
  52.                 contentLen = fs.Read(buff, 0, buffLength);
  53.                 while (contentLen != 0)
  54.                 {
  55.                     strm.Write(buff, 0, contentLen);
  56.                     contentLen = fs.Read(buff, 0, buffLength);
  57.                 }
  58.                 strm.Close();
  59.                 fs.Close();
  60.             }
  61.             catch (Exception ex)
  62.             {
  63.             }
  64.         }

  65.         /// <summary>
  66.         /// 下载
  67.         /// </summary>
  68.         /// <param name="filePath"></param>
  69.         /// <param name="fileName"></param>
  70.         public string Download(string filePath, string fileName)
  71.         {
  72.             FtpWebRequest reqFTP;
  73.             try
  74.             {
  75.                 FileStream outputStream = new FileStream(filePath + "\" + fileName, FileMode.Create);

  76.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
  77.                 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  78.                 reqFTP.UseBinary = true;
  79.                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  80.                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  81.                 Stream ftpStream = response.GetResponseStream();
  82.                 long cl = response.ContentLength;
  83.                 int bufferSize = 2048;
  84.                 int readCount;
  85.                 byte[] buffer = new byte[bufferSize];

  86.                 readCount = ftpStream.Read(buffer, 0, bufferSize);
  87.                 while (readCount > 0)
  88.                 {
  89.                     outputStream.Write(buffer, 0, readCount);
  90.                     readCount = ftpStream.Read(buffer, 0, bufferSize);
  91.                 }

  92.                 ftpStream.Close();
  93.                 outputStream.Close();
  94.                 response.Close();
  95.             }
  96.             catch (Exception ex)
  97.             {
  98.                 return fileName + " 下载失败 --> " + ex.Message;
  99.             }

  100.             return string.Empty;
  101.         }


  102.         /// <summary>
  103.         /// 删除文件
  104.         /// </summary>
  105.         /// <param name="fileName"></param>
  106.         public string Delete(string fileName)
  107.         {
  108.             try
  109.             {
  110.                 string uri = ftpURI + fileName;
  111.                 FtpWebRequest reqFTP;
  112.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

  113.                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  114.                 reqFTP.KeepAlive = false;
  115.                 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

  116.                 string result = String.Empty;
  117.                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  118.                 long size = response.ContentLength;
  119.                 Stream datastream = response.GetResponseStream();
  120.                 StreamReader sr = new StreamReader(datastream);
  121.                 result = sr.ReadToEnd();
  122.                 sr.Close();
  123.                 datastream.Close();
  124.                 response.Close();
  125.             }
  126.             catch (Exception ex)
  127.             {
  128.                 return "删除失败 --> " + ex.Message + "  文件名:" + fileName;
  129.             }

  130.             return string.Empty;
  131.         }

  132.         /// <summary>
  133.         /// 删除文件夹
  134.         /// </summary>
  135.         /// <param name="folderName"></param>
  136.         public void RemoveDirectory(string folderName)
  137.         {
  138.             try
  139.             {
  140.                 string uri = ftpURI + folderName;
  141.                 FtpWebRequest reqFTP;
  142.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

  143.                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  144.                 reqFTP.KeepAlive = false;
  145.                 reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;

  146.                 string result = String.Empty;
  147.                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  148.                 long size = response.ContentLength;
  149.                 Stream datastream = response.GetResponseStream();
  150.                 StreamReader sr = new StreamReader(datastream);
  151.                 result = sr.ReadToEnd();
  152.                 sr.Close();
  153.                 datastream.Close();
  154.                 response.Close();
  155.             }
  156.             catch (Exception ex)
  157.             {
  158.             }
  159.         }

  160.         /// <summary>
  161.         /// 获取当前目录下明细(包含文件和文件夹)
  162.         /// </summary>
  163.         /// <returns></returns>
  164.         public string[] GetFilesDetailList()
  165.         {
  166.             string[] downloadFiles;
  167.             try
  168.             {
  169.                 StringBuilder result = new StringBuilder();
  170.                 FtpWebRequest ftp;
  171.                 ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
  172.                 ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  173.                 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  174.                 WebResponse response = ftp.GetResponse();
  175.                 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);

  176.                 //while (reader.Read() > 0)
  177.                 //{

  178.                 //}
  179.                 string line = reader.ReadLine();
  180.                 //line = reader.ReadLine();
  181.                 //line = reader.ReadLine();

  182.                 while (line != null)
  183.                 {
  184.                     result.Append(line);
  185.                     result.Append("\n");
  186.                     line = reader.ReadLine();
  187.                 }
  188.                 result.Remove(result.ToString().LastIndexOf("\n"), 1);
  189.                 reader.Close();
  190.                 response.Close();
  191.                 return result.ToString().Split('\n');
  192.             }
  193.             catch (Exception ex)
  194.             {
  195.                 return null;
  196.             }
  197.         }

  198.         /// <summary>
  199.         /// 获取当前目录下文件列表(仅文件)
  200.         /// </summary>
  201.         /// <returns></returns>
  202.         public string[] GetFileList(string mask)
  203.         {
  204.             StringBuilder result = new StringBuilder();
  205.             FtpWebRequest reqFTP;
  206.             try
  207.             {
  208.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
  209.                 reqFTP.UseBinary = true;
  210.                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  211.                 reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
  212.                 WebResponse response = reqFTP.GetResponse();
  213.                 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);

  214.                 string line = reader.ReadLine();
  215.                 while (line != null)
  216.                 {
  217.                     if (line.ToLower().IndexOf(mask) > 0)
  218.                     {
  219.                         result.Append(line);
  220.                         result.Append("\n");
  221.                     }
  222.                     //if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
  223.                     //{
  224.                     //    string mask_ = mask.Substring(0, mask.IndexOf("*"));
  225.                     //    if (line.Substring(0, mask_.Length) == mask_)
  226.                     //    {
  227.                     //        result.Append(line);
  228.                     //        result.Append("\n");
  229.                     //    }
  230.                     //}
  231.                     //else
  232.                     //{
  233.                     //    result.Append(line);
  234.                     //    result.Append("\n");
  235.                     //}
  236.                     line = reader.ReadLine();
  237.                 }
  238.                 result.Remove(result.ToString().LastIndexOf('\n'), 1);
  239.                 reader.Close();
  240.                 response.Close();
  241.                 return result.ToString().Split('\n');
  242.             }
  243.             catch (Exception ex)
  244.             {
  245.                 return null;
  246.             }
  247.         }

  248.         /// <summary>
  249.         /// 获取当前目录下所有的文件夹列表(仅文件夹)
  250.         /// </summary>
  251.         /// <returns></returns>
  252.         public string[] GetDirectoryList()
  253.         {
  254.             string[] drectory = GetFilesDetailList();
  255.             string m = string.Empty;
  256.             foreach (string str in drectory)
  257.             {
  258.                 int dirPos = str.IndexOf("<DIR>");
  259.                 if (dirPos > 0)
  260.                 {
  261.                     /*判断 Windows 风格*/
  262.                     m += str.Substring(dirPos + 5).Trim() + "\n";
  263.                 }
  264.                 else if (str.Trim().Substring(0, 1).ToUpper() == "D")
  265.                 {
  266.                     /*判断 Unix 风格*/
  267.                     string dir = str.Substring(54).Trim();
  268.                     if (dir != "." && dir != "..")
  269.                     {
  270.                         m += dir + "\n";
  271.                     }
  272.                 }
  273.             }

  274.             char[] n = new char[] { '\n' };
  275.             return m.Split(n);
  276.         }

  277.         /// <summary>
  278.         /// 判断当前目录下指定的子目录是否存在
  279.         /// </summary>
  280.         /// <param name="RemoteDirectoryName">指定的目录名</param>
  281.         public bool DirectoryExist(string RemoteDirectoryName)
  282.         {
  283.             string[] dirList = GetDirectoryList();
  284.             foreach (string str in dirList)
  285.             {
  286.                 if (str.Trim() == RemoteDirectoryName.Trim())
  287.                 {
  288.                     return true;
  289.                 }
  290.             }
  291.             return false;
  292.         }

  293.         /// <summary>
  294.         /// 判断当前目录下指定的文件是否存在
  295.         /// </summary>
  296.         /// <param name="RemoteFileName">远程文件名</param>
  297.         public bool FileExist(string RemoteFileName)
  298.         {
  299.             string[] fileList = GetFileList("*.*");
  300.             foreach (string str in fileList)
  301.             {
  302.                 if (str.Trim() == RemoteFileName.Trim())
  303.                 {
  304.                     return true;
  305.                 }
  306.             }
  307.             return false;
  308.         }

  309.         /// <summary>
  310.         /// 创建文件夹
  311.         /// </summary>
  312.         /// <param name="dirName"></param>
  313.         public void MakeDir(string dirName)
  314.         {
  315.             FtpWebRequest reqFTP;
  316.             try
  317.             {
  318.                 // dirName = name of the directory to create.
  319.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
  320.                 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
  321.                 reqFTP.UseBinary = true;
  322.                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  323.                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  324.                 Stream ftpStream = response.GetResponseStream();

  325.                 ftpStream.Close();
  326.                 response.Close();
  327.             }
  328.             catch (Exception ex)
  329.             {
  330.             }
  331.         }

  332.         /// <summary>
  333.         /// 获取指定文件大小
  334.         /// </summary>
  335.         /// <param name="filename"></param>
  336.         /// <returns></returns>
  337.         public long GetFileSize(string filename)
  338.         {
  339.             FtpWebRequest reqFTP;
  340.             long fileSize = 0;
  341.             try
  342.             {
  343.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
  344.                 reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
  345.                 reqFTP.UseBinary = true;
  346.                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  347.                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  348.                 Stream ftpStream = response.GetResponseStream();
  349.                 fileSize = response.ContentLength;

  350.                 ftpStream.Close();
  351.                 response.Close();
  352.             }
  353.             catch (Exception ex)
  354.             {
  355.             }
  356.             return fileSize;
  357.         }

  358.         /// <summary>
  359.         /// 改名
  360.         /// </summary>
  361.         /// <param name="currentFilename"></param>
  362.         /// <param name="newFilename"></param>
  363.         public void ReName(string currentFilename, string newFilename)
  364.         {
  365.             FtpWebRequest reqFTP;
  366.             try
  367.             {
  368.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
  369.                 reqFTP.Method = WebRequestMethods.Ftp.Rename;
  370.                 reqFTP.RenameTo = newFilename;
  371.                 reqFTP.UseBinary = true;
  372.                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  373.                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  374.                 Stream ftpStream = response.GetResponseStream();

  375.                 ftpStream.Close();
  376.                 response.Close();
  377.             }
  378.             catch (Exception ex)
  379.             {
  380.             }
  381.         }

  382.         /// <summary>
  383.         /// 移动文件
  384.         /// </summary>
  385.         /// <param name="currentFilename"></param>
  386.         /// <param name="newFilename"></param>
  387.         public void MovieFile(string currentFilename, string newDirectory)
  388.         {
  389.             ReName(currentFilename, newDirectory);
  390.         }

  391.         /// <summary>
  392.         /// 切换当前目录
  393.         /// </summary>
  394.         /// <param name="DirectoryName"></param>
  395.         /// <param name="IsRoot">true 绝对路径   false 相对路径</param>
  396.         public void GotoDirectory(string DirectoryName, bool IsRoot)
  397.         {
  398.             if (IsRoot)
  399.             {
  400.                 ftpRemotePath = DirectoryName;
  401.             }
  402.             else
  403.             {
  404.                 ftpRemotePath += DirectoryName + "/";
  405.             }
  406.             ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
  407.         }
  408.     }
复制代码






上一篇:解决centos中文文件名乱码
下一篇:微信公众号在联通网络下jssdk签名错误的解决办法
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To:help@itsvse.com

QQ|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2026-10-16 22:49

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表