• C# ftp 文件增删改查、移动操作


      1 using System;
      2 using System.Collections.Generic;
      3 using System.Data.OleDb;
      4 using System.IO;
      5 using System.Linq;
      6 using System.Net;
      7 using System.Text;
      8 using System.Windows.Forms;
      9 
     10 namespace GateProject
     11 {
     12     public class FtpUpDown
     13     {
     14         private string strFtpServerIP;
     15 
     16         private string strFtpUserId;
     17 
     18         private string strFtpPassword;
     19 
     20         private string strFtpPort="21";
     21 
     22         private FtpWebRequest objReqFtp = null;
     23 
     24         /// <summary>
     25         /// 连接ftp
     26         /// </summary>
     27         /// <param name="path"></param>
     28         private void Connect(String path)
     29         {
     30 
     31             // 根据uri创建FtpWebRequest对象
     32             objReqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
     33 
     34             // 指定数据传输类型
     35             //To transmit text data, change the UseBinary property from its default value ( true) to false.
     36             objReqFtp.UseBinary = true;
     37 
     38             // specifies that an SSL connection
     39             objReqFtp.EnableSsl = false;
     40 
     41             // ftp用户名和密码
     42             objReqFtp.Credentials = new NetworkCredential(strFtpUserId, strFtpPassword);
     43 
     44         }
     45 
     46         /// <summary>
     47         /// 初始化
     48         /// </summary>
     49         /// <param name="strFtpServerIp"></param>
     50         /// <param name="strFtpUserId"></param>
     51         /// <param name="strFtpPassword"></param>
     52         public FtpUpDown()
     53         {
     54 
     55             try
     56             {
     57                 //获取ftp服务器连接凭证
     58                 //此处省略一些代码 66                 this.strFtpServerIP = Credentials[0];
     67                 this.strFtpUserId = Credentials[1];
     68                 this.strFtpPassword = Credentials[2];
     69  75             }
     76             catch (Exception ee)
     77             {
     78                 MessageBox.Show("连接ftp服务器失败!/r/n"+ee.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
     79             }
     80             
     81         }
     82         
     83         /// <summary>
     84         /// 从ftp服务器上获得文件列表
     85         /// </summary>
     86         /// <param name="path"></param>
     87         /// <param name="WRMethods"></param>
     88         /// <returns></returns>
     89         private string[] GetFileList(string path, string WRMethods)
     90         {
     91             string[] downloadFiles;
     92             StringBuilder result = new StringBuilder();
     93             Encoding pEncoding = Encoding.Default;
     94             try
     95             {
     96                 Connect(path);
     97 
     98                 objReqFtp.Method = WRMethods;
     99 
    100                 WebResponse response = objReqFtp.GetResponse();
    101 
    102                 StreamReader readStream;
    103 
    104                 pEncoding = GetEncodingEncode(response);
    105 
    106                 readStream = new StreamReader(response.GetResponseStream(), pEncoding);//中文文件名
    107                 //readStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
    108                 string line = readStream.ReadLine();
    109 
    110                 while (line != null)
    111                 {
    112                     result.Append(line);
    113 
    114                     result.Append("
    ");
    115 
    116                     line = readStream.ReadLine();
    117 
    118                 }
    119 
    120                 // to remove the trailing '
    '
    121 
    122                 result.Remove(result.ToString().LastIndexOf('
    '), 1);
    123 
    124                 readStream.Close();
    125 
    126                 response.Close();
    127 
    128                 objReqFtp = null;
    129 
    130                 return result.ToString().Split('
    ');
    131 
    132             }
    133 
    134             catch (Exception ex)
    135 
    136             {
    137                 MessageBox.Show(ex.Message);
    138 
    139                 downloadFiles = null;
    140 
    141                 return downloadFiles;
    142             }
    143         }
    144         /// <summary>
    145         /// 获取编码方式
    146         /// </summary>
    147         /// <param name="response"></param>
    148         /// <returns></returns>
    149         private static Encoding GetEncodingEncode(WebResponse response)
    150         {
    151             Encoding encodingTemp=Encoding.Default;
    152 
    153             StreamReader reader = new StreamReader(response.GetResponseStream());
    154 
    155             encodingTemp = reader.CurrentEncoding;
    156 
    157             if (encodingTemp == Encoding.UTF8)
    158             {
    159                 encodingTemp = Encoding.UTF8;
    160             }
    161             else if(encodingTemp == Encoding.Default)
    162             {
    163                 encodingTemp = Encoding.GetEncoding("GB2312");
    164             }
    165             else
    166             {
    167                 
    168             }
    169 
    170             return encodingTemp;
    171         }
    172 
    173         /// <summary>
    174         /// 从ftp服务器上获得特定路径中文件列表
    175         /// </summary>
    176         /// <param name="path"></param>
    177         /// <returns></returns>
    178         public string[] GetFileList(string path)
    179         {
    180             return GetFileList("ftp://" + strFtpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
    181         }
    182 
    183         /// <summary>
    184         /// 获取ftp服务器文件列表
    185         /// </summary>
    186         /// <returns></returns>
    187         public string[] GetFileList()
    188         {
    189             return GetFileList("ftp://" + strFtpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
    190         }
    191 
    192         /// <summary>
    193         /// 向ftp服务器上载文件
    194         /// </summary>
    195         /// <param name="filename">文件名</param>
    196         /// <param name="targetPath">目标文件上载路径,不含IP地址</param>
    197         public void Upload(string filename,string targetPath)
    198         {
    199             FileInfo fileInf = new FileInfo(filename);
    200 
    201             string uri = "ftp://" + strFtpServerIP + ":" + strFtpPort + "/" + targetPath ;
    202 
    203             Connect(uri);//连接        
    204 
    205             // 默认为true,连接不会被关闭
    206 
    207             // 在一个命令之后被执行
    208 
    209             objReqFtp.KeepAlive = false;
    210 
    211             // 指定执行什么命令
    212 
    213             objReqFtp.Method = WebRequestMethods.Ftp.UploadFile;
    214 
    215             // 上传文件时通知服务器文件的大小
    216 
    217             objReqFtp.ContentLength = fileInf.Length;
    218             // 缓冲大小设置为kb 
    219             int buffLength = 2048;
    220             byte[] buff = new byte[buffLength];
    221 
    222             int contentLen;
    223 
    224             // 打开一个文件流(System.IO.FileStream) 去读上传的文件
    225 
    226             FileStream fs = fileInf.OpenRead();
    227 
    228             try
    229 
    230             {
    231 
    232                 // 把上传的文件写入流
    233                 Stream strm = objReqFtp.GetRequestStream();
    234 
    235                 // 每次读文件流的kb
    236                 contentLen = fs.Read(buff, 0, buffLength);
    237 
    238                 // 流内容没有结束
    239                 while (contentLen != 0)
    240                 {
    241                     // 把内容从file stream 写入upload stream 
    242                     strm.Write(buff, 0, contentLen);
    243                     contentLen = fs.Read(buff, 0, buffLength);
    244 
    245                 }
    246 
    247                 // 关闭两个流
    248                 strm.Close();
    249                 fs.Close();
    250                 objReqFtp = null;
    251 
    252             }
    253             catch (Exception ex)
    254             {
    255 
    256                 MessageBox.Show(ex.Message, "Upload Error");
    257 
    258             }
    259 
    260         }
    261 
    262         /// <summary>
    263         /// 从ftp服务器下载文件
    264         /// </summary>
    265         /// <param name="filePath"></param>
    266         /// <param name="fileName"></param>
    267         /// <param name="errorinfo"></param>
    268         /// <returns></returns>
    269         public bool Download(string filePath, string fileName, out string errorinfo)
    270         {
    271             try
    272             {
    273                 String onlyFileName = Path.GetFileName(fileName);
    274 
    275                 string newFileName = filePath + "\" + onlyFileName;
    276 
    277                 if (File.Exists(newFileName))
    278                 {
    279                     errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);
    280                     return false;
    281                 }
    282                 string url = "ftp://" + strFtpServerIP + ":" + strFtpPort + fileName;
    283                 Connect(url);//连接 
    284                 objReqFtp.Credentials = new NetworkCredential(strFtpUserId, strFtpPassword);
    285                 FtpWebResponse response = (FtpWebResponse)objReqFtp.GetResponse();
    286                 Stream ftpStream = response.GetResponseStream();
    287                 long cl = response.ContentLength;
    288                 int bufferSize = 2048;
    289                 int readCount;
    290                 byte[] buffer = new byte[bufferSize];
    291                 readCount = ftpStream.Read(buffer, 0, bufferSize);
    292 
    293                 FileStream outputStream = new FileStream(newFileName, FileMode.Create);
    294 
    295                 while (readCount > 0)
    296                 {
    297                     outputStream.Write(buffer, 0, readCount);
    298                     readCount = ftpStream.Read(buffer, 0, bufferSize);
    299                 }
    300                 ftpStream.Close();
    301                 outputStream.Close();
    302                 response.Close();
    303 
    304                 objReqFtp = null;
    305                 errorinfo = outputStream.Name;
    306                 return true;
    307 
    308             }
    309             catch (Exception ex)
    310             {
    311                 errorinfo = string.Format("因{0},无法下载", ex.Message);
    312                 return false;
    313             }
    314 
    315         }
    316 
    317         /// <summary>
    318         /// 检测目录是否存在
    319         /// </summary> 
    320         /// <param name="ftpFilePath"></param>
    321         /// <returns>false不存在,true存在</returns>
    322         public bool DirectoryIsExist(string ftpFilePath)
    323         {
    324             WebResponse webResponse=null;
    325             StreamReader reader=null;
    326             try
    327             {
    328                 int s = ftpFilePath.LastIndexOf('/');
    329                 if (s == ftpFilePath.Length - 1)
    330                 {
    331                     ftpFilePath = ftpFilePath.Substring(0, ftpFilePath.Length - 1);
    332                               s = ftpFilePath.LastIndexOf('/');
    333                 }
    334                 string ftpFileName = ftpFilePath.Substring(s + 1, ftpFilePath.Length - s - 1);
    335                 string uri = GetFtpUri(ftpFilePath.Substring(0, s + 1));
    336 
    337                 Connect(uri);
    338 
    339                 objReqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
    340                 objReqFtp.UsePassive = false;
    341                 objReqFtp.KeepAlive = false;
    342 
    343                 webResponse = objReqFtp.GetResponse();
    344                 reader = new StreamReader(webResponse.GetResponseStream());
    345                 string line = reader.ReadLine();
    346                 while (line != null)
    347                 {
    348                     if (line == ftpFileName)
    349                     {
    350                         return true;
    351                     }
    352                     line = reader.ReadLine();
    353                 }
    354             }
    355             catch (Exception e)
    356             {
    357                 return false; 
    358             }
    359             finally
    360             {
    361                 if (reader != null)
    362                 {
    363                     reader.Close();
    364                 }
    365                 if (webResponse != null)
    366                 {
    367                     webResponse.Close();
    368                 }
    369 
    370                 objReqFtp = null;
    371             }
    372             return false;
    373         }
    374 
    375         /// <summary>
    376         /// 
    377         /// </summary>
    378         /// <param name="substring"></param>
    379         /// <returns></returns>
    380         private string GetFtpUri(string substring)
    381         {
    382             string uri = "ftp://" + strFtpServerIP + ":" + strFtpPort + "/" + substring;
    383              return uri;
    384         }
    385 
    386 
    387         /// <summary>
    388         /// 删除文件
    389         /// </summary>
    390         /// <param name="fileName"></param>
    391         public bool DeleteFileName(string fileName)
    392         {
    393             try
    394             {
    395                 FileInfo fileInf = new FileInfo(fileName);
    396 
    397                 string uri = "ftp://" + strFtpServerIP + ":" + strFtpPort + fileName;
    398 
    399                 Connect(uri);//连接        
    400 
    401                 // 默认为true,连接不会被关闭
    402 
    403                 // 在一个命令之后被执行
    404 
    405                 objReqFtp.KeepAlive = false;
    406 
    407                 // 指定执行什么命令
    408 
    409                 objReqFtp.Method = WebRequestMethods.Ftp.DeleteFile;
    410 
    411                 FtpWebResponse response = (FtpWebResponse)objReqFtp.GetResponse();
    412 
    413                 bool success = response.StatusCode == FtpStatusCode.CommandOK || response.StatusCode == FtpStatusCode.FileActionOK;
    414 
    415                 response.Close();
    416 
    417                 objReqFtp = null;
    418 
    419                 return success;
    420 
    421             }
    422             catch (Exception ex)
    423             {
    424                 MessageBox.Show(ex.Message, "删除错误");
    425                 return false;
    426             }
    427 
    428         }
    429         
    430         /// <summary>
    431         /// 创建目录
    432         /// </summary>
    433         /// <param name="dirName">目录名称,不包括IP</param>
    434         public void MakeDir(string dirName)
    435         {
    436             try
    437             {
    438                 string uri = "ftp://" + strFtpServerIP + "/" + dirName;
    439 
    440                 Connect(uri);//连接
    441 
    442                 objReqFtp.Method = WebRequestMethods.Ftp.MakeDirectory;
    443 
    444                 FtpWebResponse response = (FtpWebResponse)objReqFtp.GetResponse();
    445 
    446                 response.Close();
    447 
    448                 objReqFtp = null;
    449 
    450             }
    451             catch (Exception ex)
    452             {
    453                 MessageBox.Show(ex.Message);
    454             }
    455 
    456         }
    457         
    458         /// <summary>
    459         /// 删除目录
    460         /// </summary>
    461         /// <param name="dirName"></param>
    462         public void DelDir(string dirName)
    463         {
    464             try
    465             {
    466                 string uri = "ftp://" + strFtpServerIP +":"+strFtpPort + dirName;
    467 
    468                 Connect(uri);//连接     
    469 
    470                 objReqFtp.Method = WebRequestMethods.Ftp.RemoveDirectory;
    471 
    472                 FtpWebResponse response = (FtpWebResponse)objReqFtp.GetResponse();
    473 
    474                 response.Close();
    475 
    476                 objReqFtp = null;
    477 
    478             }
    479             catch (Exception ex)
    480             {
    481                 MessageBox.Show(ex.Message);
    482             }
    483 
    484         }
    485         
    486         /// <summary>
    487         /// 获得文件大小
    488         /// </summary>
    489         /// <param name="filename"></param>
    490         /// <returns></returns>
    491         public long GetFileSize(string filename)
    492         {
    493             long fileSize = 0;
    494             try
    495             {
    496                 FileInfo fileInf = new FileInfo(filename);
    497 
    498                 string uri = "ftp://" + strFtpServerIP + "/" + fileInf.Name;
    499 
    500                 Connect(uri);//连接     
    501 
    502                 objReqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
    503 
    504                 FtpWebResponse response = (FtpWebResponse)objReqFtp.GetResponse();
    505 
    506                 fileSize = response.ContentLength;
    507 
    508                 response.Close();
    509 
    510                 objReqFtp = null;
    511             }
    512             catch (Exception ex)
    513             {
    514                 MessageBox.Show(ex.Message);
    515             }
    516 
    517             return fileSize;
    518 
    519         }
    520         
    521         /// <summary>
    522         /// 文件重命名,包括ftp服务器内移动,但目标目录若已有同名文件,则会发生错误,原文件会被删除
    523         /// 524         /// </summary>
    525         /// <param name="currentFilename">当前目录[不含IP]</param>
    526         /// <param name="newFilename">新目录[不含IP]</param>
    527         public bool Rename(string currentFilename, string newFilename)
    528         {
    529             try
    530             {
    531                 FileInfo fileInf = new FileInfo(currentFilename);
    532 
    533                 string uri = "ftp://" + strFtpServerIP + ":" + strFtpPort + currentFilename;
    534 
    535                 Connect(uri);//连接
    536 
    537                 objReqFtp.Method = System.Net.WebRequestMethods.Ftp.Rename;
    538                 //Wr.RenameTo = "/"+"someotherDirectory" + "/" +"file.txt";
    539                 objReqFtp.RenameTo = newFilename;
    540 
    541                 FtpWebResponse response = (FtpWebResponse)objReqFtp.GetResponse();
    542 
    543                 Stream ftpStream = response.GetResponseStream();
    544 
    545                 if (ftpStream != null) ftpStream.Close();
    546                 
    547                 bool success = response.StatusCode == FtpStatusCode.CommandOK || response.StatusCode == FtpStatusCode.FileActionOK;
    548                 
    549                 response.Close();
    550 
    551                 objReqFtp = null;
    552 
    553                 return success;
    554             }
    555 
    556             catch (Exception ex)
    557 
    558             {
    559 
    560                 MessageBox.Show(ex.Message);
    561                 return false;
    562 
    563             }
    564 
    565         }
    566         
    567         /// <summary>
    568         /// 获得文件明细
    569         /// </summary>
    570         /// <returns></returns>
    571         public string[] GetFilesDetailList()
    572         {
    573             return GetFileList("ftp://" + strFtpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
    574         }
    575 
    576         /// <summary>
    577         /// 获得特定路径下的文件明细
    578         /// </summary>
    579         /// <param name="path"></param>
    580         /// <returns></returns>
    581         public string[] GetFilesDetailList(string path)
    582         {
    583             return GetFileList("ftp://" + strFtpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
    584         }
    585 
    586     }
    587 }
    588 
    589 
    590 
    591     

    参考了如下网站内容并做了相应修改和完善

    http://zhufangzeng.blog.163.com/blog/static/249191412010668453343/

    https://social.msdn.microsoft.com/Forums/en-US/fc669934-d6d2-4815-b1ea-9a06006f05b7/moving-a-file-from-one-folder-to-another-ftp?forum=netfxnetcom&prof=required

  • 相关阅读:
    js的单元测试
    如何嵌入HTML 页面
    使用JQuery时间比较
    @page指令ValidateRequest的作用
    时间的正则表达式(比较简单)
    [置顶] Android代码 监控手机电池的状态
    [置顶] Android代码传感器光传感
    [置顶] Android问题ViewPager实现左右两个屏幕的切换
    [置顶] Android代码传感器测试手机支持那几种传感
    [置顶] Android代码检测手机耳机插拔
  • 原文地址:https://www.cnblogs.com/5igis/p/5igis_11825.html
Copyright © 2020-2023  润新知