• Ftp操作类


    FtpWeb.cs

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Text;
      4 using System.IO;
      5 using System.Net;
      6 using System.Windows.Forms;
      7 using System.Globalization;
      8 
      9 namespace SearchPicture
     10 {
     11 
     12     public class FtpWeb
     13     {
     14         string ftpServerIP;
     15         string ftpRemotePath;
     16         string ftpUserID;
     17         string ftpPassword;
     18         string ftpURI;
     19         int ftpPort;
     20 
     21         /// <summary>
     22         /// 连接FTP
     23         /// </summary>
     24         /// <param name="FtpServerIP">FTP连接地址</param>
     25         /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
     26         /// <param name="FtpUserID">用户名</param>
     27         /// <param name="FtpPassword">密码</param>
     28         public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
     29         {
     30             ftpServerIP = FtpServerIP;
     31             ftpRemotePath = FtpRemotePath;
     32             ftpUserID = FtpUserID;
     33             ftpPassword = FtpPassword;
     34             ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
     35         }
     36 
     37         /// <summary>
     38         /// ftp连接
     39         /// </summary>
     40         /// <param name="FtpServerIP"></param>
     41         /// <param name="FtpPort"></param>
     42         /// <param name="FtpRemotePath"></param>
     43         /// <param name="FtpUserID"></param>
     44         /// <param name="FtpPassword"></param>
     45         public FtpWeb(string FtpServerIP, int FtpPort, string FtpRemotePath, string FtpUserID, string FtpPassword)
     46         {
     47             ftpServerIP = FtpServerIP;
     48             ftpRemotePath = FtpRemotePath;
     49             ftpUserID = FtpUserID;
     50             ftpPassword = FtpPassword;
     51             ftpPort = FtpPort;
     52             ftpURI = string.Format("ftp://{0}:{1}/",ftpServerIP,FtpPort);
     53             if (!string.IsNullOrEmpty(FtpRemotePath))
     54             {
     55                 ftpURI = string.Format("{0}{1}/",ftpURI,FtpRemotePath);
     56             }
     57         }
     58 
     59         /// <summary>
     60         /// 上传
     61         /// </summary>
     62         /// <param name="filename"></param>
     63         public void Upload(string filename)
     64         {
     65             FileInfo fileInf = new FileInfo(filename);
     66             string uri = ftpURI + fileInf.Name;
     67             FtpWebRequest reqFTP;
     68 
     69             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
     70             reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
     71             reqFTP.KeepAlive = false;
     72             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
     73             reqFTP.UseBinary = true;
     74             reqFTP.ContentLength = fileInf.Length;
     75             int buffLength = 2048;
     76             byte[] buff = new byte[buffLength];
     77             int contentLen;
     78             FileStream fs = fileInf.OpenRead();
     79             try
     80             {
     81                 Stream strm = reqFTP.GetRequestStream();
     82                 contentLen = fs.Read(buff, 0, buffLength);
     83                 while (contentLen != 0)
     84                 {
     85                     strm.Write(buff, 0, contentLen);
     86                     contentLen = fs.Read(buff, 0, buffLength);
     87                 }
     88                 strm.Close();
     89                 fs.Close();
     90             }
     91             catch (Exception ex)
     92             {
     93                 throw new Exception("上传文件出错!", ex);
     94             }
     95         }
     96 
     97         /// <summary>
     98         /// 下载
     99         /// </summary>
    100         /// <param name="filePath"></param>
    101         /// <param name="fileName"></param>
    102         public void Download(string filePath, string fileName)
    103         {
    104             FtpWebRequest reqFTP;
    105             try
    106             {
    107                 FileStream outputStream = new FileStream(filePath + "\" + fileName, FileMode.Create);
    108 
    109                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
    110                 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
    111                 reqFTP.UseBinary = true;
    112                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    113                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    114                 Stream ftpStream = response.GetResponseStream();
    115                 long cl = response.ContentLength;
    116                 int bufferSize = 2048;
    117                 int readCount;
    118                 byte[] buffer = new byte[bufferSize];
    119 
    120                 readCount = ftpStream.Read(buffer, 0, bufferSize);
    121                 while (readCount > 0)
    122                 {
    123                     outputStream.Write(buffer, 0, readCount);
    124                     readCount = ftpStream.Read(buffer, 0, bufferSize);
    125                 }
    126 
    127                 ftpStream.Close();
    128                 outputStream.Close();
    129                 response.Close();
    130             }
    131             catch (Exception ex)
    132             {
    133                 throw new Exception("下载文件出错!", ex);
    134             }
    135         }
    136 
    137 
    138         /// <summary>
    139         /// 删除文件
    140         /// </summary>
    141         /// <param name="fileName"></param>
    142         public void Delete(string fileName)
    143         {
    144             try
    145             {
    146                 string uri = ftpURI + fileName;
    147                 FtpWebRequest reqFTP;
    148                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    149 
    150                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    151                 reqFTP.KeepAlive = false;
    152                 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
    153 
    154                 string result = String.Empty;
    155                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    156                 long size = response.ContentLength;
    157                 Stream datastream = response.GetResponseStream();
    158                 StreamReader sr = new StreamReader(datastream);
    159                 result = sr.ReadToEnd();
    160                 sr.Close();
    161                 datastream.Close();
    162                 response.Close();
    163             }
    164             catch (Exception ex)
    165             {
    166                 throw new Exception("删除文件!", ex);
    167             }
    168         }
    169 
    170         /// <summary>
    171         /// 删除文件夹
    172         /// </summary>
    173         /// <param name="folderName"></param>
    174         public void RemoveDirectory(string folderName)
    175         {
    176             try
    177             {
    178                 string uri = ftpURI + folderName;
    179                 FtpWebRequest reqFTP;
    180                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    181 
    182                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    183                 reqFTP.KeepAlive = false;
    184                 reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
    185 
    186                 string result = String.Empty;
    187                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    188                 long size = response.ContentLength;
    189                 Stream datastream = response.GetResponseStream();
    190                 StreamReader sr = new StreamReader(datastream);
    191                 result = sr.ReadToEnd();
    192                 sr.Close();
    193                 datastream.Close();
    194                 response.Close();
    195             }
    196             catch (Exception ex)
    197             {
    198 
    199                 throw new Exception("删除文件夹!", ex);
    200             }
    201         }
    202 
    203         /// <summary>
    204         /// 获取当前目录下明细(包含文件和文件夹)
    205         /// </summary>
    206         /// <returns></returns>
    207         public string[] GetFilesDetailList()
    208         {
    209             string[] downloadFiles;
    210             try
    211             {
    212                 StringBuilder result = new StringBuilder();
    213                 FtpWebRequest ftp;
    214                 ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
    215                 ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    216                 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    217                 WebResponse response = ftp.GetResponse();
    218                 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
    219 
    220                 //while (reader.Read() > 0)
    221                 //{
    222 
    223                 //}
    224                 string line = reader.ReadLine();
    225                 //line = reader.ReadLine();
    226                 //line = reader.ReadLine();
    227 
    228                 while (line != null)
    229                 {
    230                     result.Append(line);
    231                     result.Append("
    ");
    232                     line = reader.ReadLine();
    233                 }
    234                 result.Remove(result.ToString().LastIndexOf("
    "), 1);
    235                 reader.Close();
    236                 response.Close();
    237                 return result.ToString().Split('
    ');
    238             }
    239             catch (Exception ex)
    240             {
    241                 throw new Exception("获取当前目录下明细(包含文件和文件夹)!", ex);
    242             }
    243         }
    244 
    245         /// <summary>
    246         /// 获取当前目录下文件列表(仅文件)
    247         /// </summary>
    248         /// <returns></returns>
    249         public string[] GetFileList(string mask)
    250         {
    251             string[] downloadFiles;
    252             StringBuilder result = new StringBuilder();
    253             FtpWebRequest reqFTP;
    254             try
    255             {
    256                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
    257                 reqFTP.UseBinary = true;
    258                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    259                 reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
    260                 WebResponse response = reqFTP.GetResponse();
    261                 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
    262 
    263                 string line = reader.ReadLine();
    264                 while (line != null)
    265                 {
    266                     if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
    267                     {
    268 
    269                         string mask_ = mask.Substring(0, mask.IndexOf("*"));
    270                         if (line.Substring(0, mask_.Length) == mask_)
    271                         {
    272                             result.Append(line);
    273                             result.Append("
    ");
    274                         }
    275                     }
    276                     else
    277                     {
    278                         result.Append(line);
    279                         result.Append("
    ");
    280                     }
    281                     line = reader.ReadLine();
    282                 }
    283                 result.Remove(result.ToString().LastIndexOf('
    '), 1);
    284                 reader.Close();
    285                 response.Close();
    286                 return result.ToString().Split('
    ');
    287             }
    288             catch (Exception ex)
    289             {
    290                 throw new Exception("获取当前目录下文件列表(仅文件)!", ex);
    291             }
    292         }
    293 
    294         /// <summary>
    295         /// 获取当前目录下所有的文件夹列表(仅文件夹)
    296         /// </summary>
    297         /// <returns></returns>
    298         public string[] GetDirectoryList()
    299         {
    300             string[] drectory = GetFilesDetailList();
    301             string m = string.Empty;
    302             foreach (string str in drectory)
    303             {
    304                 int dirPos = str.IndexOf("<DIR>");
    305                 if (dirPos > 0)
    306                 {
    307                     /*判断 Windows 风格*/
    308                     m += str.Substring(dirPos + 5).Trim() + "
    ";
    309                 }
    310                 else if (str.Trim().Substring(0, 1).ToUpper() == "D")
    311                 {
    312                     /*判断 Unix 风格*/
    313                     string dir = str.Substring(54).Trim();
    314                     if (dir != "." && dir != "..")
    315                     {
    316                         m += dir + "
    ";
    317                     }
    318                 }
    319             }
    320 
    321             char[] n = new char[] { '
    ' };
    322             return m.Split(n);
    323         }
    324 
    325         /// <summary>
    326         /// 判断当前目录下指定的子目录是否存在
    327         /// </summary>
    328         /// <param name="RemoteDirectoryName">指定的目录名</param>
    329         public bool DirectoryExist(string RemoteDirectoryName)
    330         {
    331             string[] dirList = GetDirectoryList();
    332             foreach (string str in dirList)
    333             {
    334                 if (str.Trim() == RemoteDirectoryName.Trim())
    335                 {
    336                     return true;
    337                 }
    338             }
    339             return false;
    340         }
    341 
    342         /// <summary>
    343         /// 判断当前目录下指定的文件是否存在
    344         /// </summary>
    345         /// <param name="RemoteFileName">远程文件名</param>
    346         public bool FileExist(string RemoteFileName)
    347         {
    348             string[] fileList = GetFileList("*.*");
    349             foreach (string str in fileList)
    350             {
    351                 if (str.Trim() == RemoteFileName.Trim())
    352                 {
    353                     return true;
    354                 }
    355             }
    356             return false;
    357         }
    358 
    359         /// <summary>
    360         /// 创建文件夹
    361         /// </summary>
    362         /// <param name="dirName"></param>
    363         public void MakeDir(string dirName)
    364         {
    365             FtpWebRequest reqFTP;
    366             try
    367             {
    368                 // dirName = name of the directory to create.
    369                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
    370                 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
    371                 reqFTP.UseBinary = true;
    372                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    373                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    374                 Stream ftpStream = response.GetResponseStream();
    375 
    376                 ftpStream.Close();
    377                 response.Close();
    378             }
    379             catch (Exception ex)
    380             {
    381                 throw new Exception("创建文件夹出错!", ex);
    382             }
    383         }
    384 
    385         /// <summary>
    386         /// 获取指定文件大小
    387         /// </summary>
    388         /// <param name="filename"></param>
    389         /// <returns></returns>
    390         public long GetFileSize(string filename)
    391         {
    392             FtpWebRequest reqFTP;
    393             long fileSize = 0;
    394             try
    395             {
    396                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
    397                 reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
    398                 reqFTP.UseBinary = true;
    399                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    400                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    401                 Stream ftpStream = response.GetResponseStream();
    402                 fileSize = response.ContentLength;
    403 
    404                 ftpStream.Close();
    405                 response.Close();
    406             }
    407             catch (Exception ex)
    408             {
    409                 throw new Exception("获取指定文件大小出错!", ex);
    410             }
    411             return fileSize;
    412         }
    413 
    414         /// <summary>
    415         /// 改名
    416         /// </summary>
    417         /// <param name="currentFilename"></param>
    418         /// <param name="newFilename"></param>
    419         public void ReName(string currentFilename, string newFilename)
    420         {
    421             FtpWebRequest reqFTP;
    422             try
    423             {
    424                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
    425                 reqFTP.Method = WebRequestMethods.Ftp.Rename;
    426                 reqFTP.RenameTo = newFilename;
    427                 reqFTP.UseBinary = true;
    428                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    429                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    430                 Stream ftpStream = response.GetResponseStream();
    431 
    432                 ftpStream.Close();
    433                 response.Close();
    434             }
    435             catch (Exception ex)
    436             {
    437                 throw new Exception("修改文件名称出错!",ex);
    438             }
    439         }
    440 
    441     }
    442 
    443 }
    View Code

    FtpWebServer.cs

      1 using System;
      2 using System.Collections.Generic;
      3 using System.IO;
      4 using System.Linq;
      5 using System.Net;
      6 using System.Text;
      7 
      8 namespace SearchPicture
      9 {
     10     /// <summary>
     11     /// 服务器操作类
     12     /// </summary>
     13     public class FtpWebServer
     14     {
     15         #region FtpWebServer 服务器操作方法
     16         string ftpServerIp;//服务器ip地址
     17         int ftpPort;//服务器端口
     18         string userName;//用户名
     19         string userPwd;//用户密码
     20         string ftpBaseUrl;//路径组成 ftp://ftpServerIp:ftpPort/
     21 
     22         /// <summary>
     23         /// 构造函数
     24         /// </summary>
     25         /// <param name="ftpServerIp">服务器地址</param>
     26         /// <param name="ftpPort">服务器端口号</param>
     27         /// <param name="userName">用户名</param>
     28         /// <param name="userPwd">用户密码</param>
     29         public FtpWebServer(string ftpServerIp, int ftpPort, string userName, string userPwd)
     30         {
     31             this.ftpServerIp = ftpServerIp;
     32             this.ftpPort = ftpPort;
     33             this.userName = userName;
     34             this.userPwd = userPwd;
     35             this.ftpBaseUrl = string.Format("ftp://{0}:{1}/", ftpServerIp, ftpPort);
     36         }
     37         #endregion
     38 
     39 
     40         //1.搜索文件夹 指定ip地址,日期范围
     41 
     42         #region SearchDir 搜索一级目录下的二级文件夹目录,指定一级目录
     43         /// <summary>
     44         /// 搜索一级目录下的二级文件夹目录,指定一级目录
     45         /// </summary>
     46         /// <param name="firstDir"></param>
     47         /// <returns></returns>
     48         public List<FtpModel> SearchDir(List<string> firstDir, string serverName)
     49         {
     50             List<FtpModel> list = new List<FtpModel>();
     51 
     52             foreach (var item in firstDir)
     53             {
     54                 try
     55                 {
     56                     var ftpUrl = string.Format("{0}{1}/", ftpBaseUrl, item);
     57 
     58                     FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUrl));
     59                     ftp.Credentials = new NetworkCredential(userName, userPwd);
     60                     ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
     61                     WebResponse response = ftp.GetResponse();
     62                     StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
     63 
     64                     string line = reader.ReadLine();
     65                     while (line != null)
     66                     {
     67 
     68                         int dirPos = line.IndexOf("<DIR>");
     69                         if (dirPos > 0)
     70                         {
     71                             /*判断 Windows 风格*/
     72                             FtpModel model = new FtpModel();
     73                             model.FtpDepartDir = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
     74                             model.FtpServerUrl = string.Format("{0}{1}/", ftpUrl, model.FtpDepartDir);
     75                             model.ServerName = serverName;
     76                             list.Add(model);
     77 
     78                         }
     79                         else if (line.Trim().Substring(0, 1).ToUpper() == "D")
     80                         {
     81                             /*判断 Unix 风格*/
     82                             string dir = line.Substring(51).Trim();
     83                             if (dir != "." && dir != "..")
     84                             {
     85                                 FtpModel model = new FtpModel();
     86                                 model.FtpDepartDir = dir;
     87                                 model.FtpServerUrl = string.Format("{0}{1}/", ftpUrl, model.FtpDepartDir);
     88                                 model.ServerName = serverName;
     89                                 list.Add(model);
     90                             }
     91                         }
     92 
     93                         line = reader.ReadLine();
     94                     }
     95                     reader.Close();
     96                     response.Close();
     97                 }
     98                 catch (Exception ex)
     99                 {
    100                     Log.LogMessage("搜索部门/班级发生错误", ex);
    101                 }
    102             }
    103             return list;
    104         }
    105         #endregion
    106 
    107         #region SearchFtpName 搜索ftp服务器名称
    108         /// <summary>
    109         /// 搜索ftp服务器名称
    110         /// </summary>
    111         /// <returns></returns>
    112         public string SearchFtpName()
    113         {
    114             string ftpName = string.Empty;
    115 
    116             FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpBaseUrl));
    117             ftp.Credentials = new NetworkCredential(userName, userPwd);
    118             ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    119             WebResponse response = ftp.GetResponse();
    120             StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
    121 
    122             string line = reader.ReadLine();
    123             while (line != null)
    124             {
    125                 if (line.Length > 51 && !line.Contains("<DIR>") && line.ToUpper().Trim().EndsWith(".TXT"))
    126                 {
    127                     //读取到服务器名称,则自动跳出
    128 
    129                     ftpName = line.Substring(51).Trim();
    130                     ftpName = ftpName.Substring(0, ftpName.LastIndexOf("."));
    131                     break;
    132                 }
    133                 line = reader.ReadLine();
    134             }
    135             reader.Close();
    136             response.Close();
    137 
    138             return ftpName;
    139         }
    140         #endregion
    141 
    142         //2.搜索文件 指定日期范围,文件夹名称
    143 
    144         #region SearchFile 搜索文件名或者搜索文件夹下的所有文件
    145         /// <summary>
    146         /// 搜索文件
    147         /// </summary>
    148         /// <param name="userName"></param>
    149         /// <param name="userPwd"></param>
    150         /// <param name="ftpUrl"></param>
    151         /// <param name="name"></param>
    152         /// <returns></returns>
    153         public static List<FtpFileModel> SearchFile(string userName, string userPwd, string ftpUrl, string name, string ftpName)
    154         {
    155             List<FtpFileModel> fileList = new List<FtpFileModel>();
    156 
    157             //搜索所有文件
    158             FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUrl));
    159             reqFTP.UseBinary = true;
    160             reqFTP.Credentials = new NetworkCredential(userName, userPwd);
    161             reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    162             WebResponse response = reqFTP.GetResponse();
    163             StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
    164 
    165             string line = reader.ReadLine();
    166             while (line != null)
    167             {
    168 
    169                 if (line.IndexOf("_") > 0 && !line.Contains("<DIR>") && line.Length > 51)
    170                 {
    171                     var fileName = line.Substring(51).Trim();
    172                     if (fileName.Substring(0, fileName.IndexOf("_")).Contains(name) || name == string.Empty)
    173                     {
    174                         FtpFileModel model = new FtpFileModel();
    175                         ChangeStringToUserInfo(fileName, model);
    176                         model.FtpFileUrl = ftpUrl + fileName;
    177                         model.ServerName = ftpName;
    178                         fileList.Add(model);
    179                     }
    180                 }
    181                 line = reader.ReadLine();
    182             }
    183             reader.Close();
    184             response.Close();
    185 
    186 
    187             return fileList;
    188         }
    189         #endregion
    190 
    191 
    192         //3.拷贝文件 指定文件路径,ip地址,本地文件路径
    193 
    194         #region CopyFile 复制文件到本地
    195         /// <summary>
    196         /// 复制文件到本地
    197         /// </summary>
    198         /// <param name="userName"></param>
    199         /// <param name="userPwd"></param>
    200         /// <param name="ftpUrl"></param>
    201         /// <param name="fileDir">本地保存文件基本路径</param>
    202         /// <returns></returns>
    203         public static bool CopyFile(string userName, string userPwd, string ftpUrl, string fileDir, ref string downloadUrl)
    204         {
    205 
    206             //检测本地文件夹是否存在,如果不存在则创建
    207             var downloadDir = ftpUrl.Replace("ftp://", "");
    208             var begin = downloadDir.IndexOf("/");
    209             var length = downloadDir.LastIndexOf("/") + 1 - begin;
    210             downloadDir = fileDir + "/" + downloadDir.Substring(begin, length);
    211             if (!Directory.Exists(downloadDir))
    212             {
    213                 Directory.CreateDirectory(downloadDir);
    214             }
    215             downloadUrl = downloadDir + "/" + Path.GetFileName(ftpUrl);
    216 
    217             if (File.Exists(downloadUrl)) return true;
    218 
    219             return CopyOnlyFile(userName, userPwd, ftpUrl, downloadUrl);
    220 
    221         }
    222         #endregion
    223 
    224         #region CopyOnlyFile 下载文件到本地
    225         /// <summary>
    226         /// 下载文件到本地
    227         /// </summary>
    228         /// <param name="userName"></param>
    229         /// <param name="userPwd"></param>
    230         /// <param name="ftpUrl"></param>
    231         /// <param name="currentUrl"></param>
    232         /// <returns></returns>
    233         public static bool CopyOnlyFile(string userName, string userPwd, string ftpUrl, string currentUrl)
    234         {
    235 
    236             FileStream outputStream = new FileStream(currentUrl, FileMode.Create);
    237             FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUrl));
    238             reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
    239             reqFTP.UseBinary = true;
    240             reqFTP.Credentials = new NetworkCredential(userName, userPwd);
    241             FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    242             Stream ftpStream = response.GetResponseStream();
    243             long cl = response.ContentLength;
    244             int bufferSize = 2048;
    245             int readCount;
    246             byte[] buffer = new byte[bufferSize];
    247 
    248             readCount = ftpStream.Read(buffer, 0, bufferSize);
    249             while (readCount > 0)
    250             {
    251                 outputStream.Write(buffer, 0, readCount);
    252                 readCount = ftpStream.Read(buffer, 0, bufferSize);
    253             }
    254 
    255             ftpStream.Close();
    256             outputStream.Close();
    257             response.Close();
    258 
    259             return true;
    260 
    261         }
    262         #endregion
    263 
    264         #region ChangeStringToUserInfo 将文件名转换为用户名和刷卡时间
    265         /// <summary>
    266         /// 将文件名转换为用户名和刷卡时间
    267         /// </summary>
    268         /// <param name="url"></param>
    269         /// <param name="model"></param>
    270         private static void ChangeStringToUserInfo(string picName, FtpFileModel model)
    271         {
    272             var ext = Path.GetExtension(picName);
    273             picName = picName.Replace(ext, string.Empty);
    274 
    275             var names = picName.Split(new char[] { '_' });
    276             var year = names[1].Substring(0, 4);
    277             var month = names[1].Substring(4, 2);
    278             var day = names[1].Substring(6, 2);
    279             var hour = names[1].Substring(8, 2);
    280             var min = names[1].Substring(10, 2);
    281             var second = names[1].Substring(12, 2);
    282             model.UserTime = string.Format("{0}-{1}-{2} {3}:{4}:{5}", year, month, day, hour, min, second);
    283             model.UserName = names[0];
    284         }
    285         #endregion
    286     }
    287 }
    View Code
  • 相关阅读:
    !!!C#——进制转换!
    冒泡排序后用二分查找法查找位置
    简陋的4位验证码程序(范围内取随机数)
    这个年龄计算程序相当不科学,体验还是差差哒
    8.7课堂随笔
    字符串中查询关键字
    !汉企的WiFi网速好快
    重度强迫症患者的九九乘法表
    自选数字和范围的整除算法
    day52
  • 原文地址:https://www.cnblogs.com/maomao999/p/3668425.html
Copyright © 2020-2023  润新知