• C# FTP操作类


    001    using System;
    002    using System.Collections.Generic;
    003    using System.Text;
    004    using System.Net;
    005    using System.IO;
    006    
    007    namespace Utility
    008    {
    009        public class FtpUpDown
    010        {
    011    
    012            string ftpServerIP;
    013    
    014            string ftpUserID;
    015    
    016            string ftpPassword;
    017    
    018            FtpWebRequest reqFTP;
    019    
    020            private void Connect(String path)//连接ftp
    021            {
    022    
    023                // 根据uri创建FtpWebRequest对象
    024    
    025                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
    026    
    027                // 指定数据传输类型
    028    
    029                reqFTP.UseBinary = true;
    030    
    031                // ftp用户名和密码
    032    
    033                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    034    
    035            }
    036    
    037            public FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword)
    038            {
    039                this.ftpServerIP = ftpServerIP;
    040    
    041                this.ftpUserID = ftpUserID;
    042    
    043                this.ftpPassword = ftpPassword;
    044            }
    045    
    046            //都调用这个
    047    
    048            private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
    049            {
    050                string[] downloadFiles;
    051                StringBuilder result = new StringBuilder();
    052                try
    053                {
    054                    Connect(path);
    055    
    056                    reqFTP.Method = WRMethods;
    057    
    058                    WebResponse response = reqFTP.GetResponse();
    059    
    060                    StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
    061    
    062                    string line = reader.ReadLine();
    063    
    064                    while (line != null)
    065                    {
    066    
    067                        result.Append(line);
    068    
    069                        result.Append("\n");
    070    
    071                        line = reader.ReadLine();
    072    
    073                    }
    074    
    075                    // to remove the trailing '\n'
    076    
    077                    result.Remove(result.ToString().LastIndexOf('\n'), 1);
    078    
    079                    reader.Close();
    080    
    081                    response.Close();
    082    
    083                    return result.ToString().Split('\n');
    084    
    085                }
    086    
    087                catch (Exception ex)
    088                {
    089                    Log.WriteError("Get FileList Error:" + ex.Message);
    090                    downloadFiles = null;
    091    
    092                    return downloadFiles;
    093                }
    094            }
    095    
    096            public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
    097            {
    098                return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
    099            }
    100            public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表
    101            {
    102                return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
    103            }
    104    
    105            public void Upload(string filename) //上面的代码实现了从ftp服务器上载文件的功能
    106            {
    107                FileInfo fileInf = new FileInfo(filename);
    108    
    109                string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
    110    
    111                Connect(uri);//连接        
    112    
    113                // 默认为true,连接不会被关闭
    114    
    115                // 在一个命令之后被执行
    116    
    117                reqFTP.KeepAlive = false;
    118    
    119                // 指定执行什么命令
    120    
    121                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
    122    
    123                // 上传文件时通知服务器文件的大小
    124    
    125                reqFTP.ContentLength = fileInf.Length;
    126                // 缓冲大小设置为kb
    127                int buffLength = 2048;
    128                byte[] buff = new byte[buffLength];
    129    
    130                int contentLen;
    131    
    132                // 打开一个文件流(System.IO.FileStream) 去读上传的文件
    133    
    134                FileStream fs = fileInf.OpenRead();
    135    
    136                try
    137                {
    138    
    139                    // 把上传的文件写入流
    140    
    141                    Stream strm = reqFTP.GetRequestStream();
    142    
    143                    // 每次读文件流的kb
    144    
    145                    contentLen = fs.Read(buff, 0, buffLength);
    146    
    147                    // 流内容没有结束
    148    
    149                    while (contentLen != 0)
    150                    {
    151                        // 把内容从file stream 写入upload stream
    152                        strm.Write(buff, 0, contentLen);
    153                        contentLen = fs.Read(buff, 0, buffLength);
    154    
    155                    }
    156    
    157                    // 关闭两个流
    158    
    159                    strm.Close();
    160    
    161                    fs.Close();
    162    
    163                }
    164    
    165                catch (Exception ex)
    166                {
    167                     Log.WriteError( "Upload Error:" + ex.Message);
    168                }
    169    
    170            }
    171    
    172            public bool Download(string filePath, string fileName, out string errorinfo)////上面的代码实现了从ftp服务器下载文件的功能
    173            {
    174                try
    175                {
    176                    String onlyFileName = Path.GetFileName(fileName);
    177    
    178                    string newFileName = filePath + "\\" + onlyFileName;
    179    
    180                    if (File.Exists(newFileName))
    181                    {
    182    
    183                        errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);
    184                        return false;
    185                    }
    186                    string url = "ftp://" + ftpServerIP + "/" + fileName;
    187                    Connect(url);//连接
    188                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    189                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    190                    Stream ftpStream = response.GetResponseStream();
    191                    long cl = response.ContentLength;
    192                    int bufferSize = 2048;
    193                    int readCount;
    194                    byte[] buffer = new byte[bufferSize];
    195                    readCount = ftpStream.Read(buffer, 0, bufferSize);
    196    
    197                    FileStream outputStream = new FileStream(newFileName, FileMode.Create);
    198                    while (readCount > 0)
    199                    {
    200                        outputStream.Write(buffer, 0, readCount);
    201                        readCount = ftpStream.Read(buffer, 0, bufferSize);
    202                    }
    203                    ftpStream.Close();
    204                    outputStream.Close();
    205                    response.Close();
    206    
    207                    errorinfo = "";
    208    
    209                    return true;
    210    
    211                }
    212    
    213                catch (Exception ex)
    214                {
    215                    errorinfo = string.Format("因{0},无法下载", ex.Message);
    216    
    217                    return false;
    218    
    219                }
    220    
    221            }
    222    
    223            //删除文件
    224    
    225            public void DeleteFileName(string fileName)
    226            {
    227                try
    228                {
    229                    FileInfo fileInf = new FileInfo(fileName);
    230    
    231                    string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
    232    
    233                    Connect(uri);//连接        
    234    
    235                    // 默认为true,连接不会被关闭
    236    
    237                    // 在一个命令之后被执行
    238    
    239                    reqFTP.KeepAlive = false;
    240    
    241                    // 指定执行什么命令
    242    
    243                    reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
    244    
    245                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    246                    response.Close();
    247    
    248                }
    249    
    250                catch (Exception ex)
    251                {
    252                    Log.WriteError("删除错误:" + ex.Message);
    253                }
    254    
    255            }
    256    
    257            //创建目录
    258    
    259            public void MakeDir(string dirName)
    260            {
    261                try
    262                {
    263                    string uri = "ftp://" + ftpServerIP + "/" + dirName;
    264    
    265                    Connect(uri);//连接     
    266    
    267                    reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
    268    
    269                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    270    
    271                    response.Close();
    272    
    273                }
    274    
    275                catch (Exception ex)
    276                {
    277                    Log.WriteError("创建目录错误:" + ex.Message);
    278                }
    279    
    280            }
    281    
    282            //删除目录
    283    
    284            public void delDir(string dirName)
    285            {
    286                try
    287                {
    288                    string uri = "ftp://" + ftpServerIP + "/" + dirName;
    289    
    290                    Connect(uri);//连接     
    291    
    292                    reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
    293    
    294                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    295    
    296                    response.Close();
    297    
    298                }
    299    
    300                catch (Exception ex)
    301                {
    302                    Log.WriteError("删除目录错误:" + ex.Message);
    303                }
    304    
    305            }
    306    
    307            //获得文件大小
    308    
    309            public long GetFileSize(string filename)
    310            {
    311    
    312    
    313    
    314                long fileSize = 0;
    315    
    316                try
    317                {
    318    
    319                    FileInfo fileInf = new FileInfo(filename);
    320    
    321                    string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
    322    
    323                    Connect(uri);//连接     
    324    
    325                    reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
    326    
    327                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    328    
    329                    fileSize = response.ContentLength;
    330    
    331                    response.Close();
    332    
    333                }
    334    
    335                catch (Exception ex)
    336                {
    337                    Log.WriteError("获得文件大小错误:" + ex.Message);
    338                }
    339    
    340                return fileSize;
    341    
    342            }
    343    
    344            //文件改名
    345    
    346            public void Rename(string currentFilename, string newFilename)
    347            {
    348                try
    349                {
    350                    FileInfo fileInf = new FileInfo(currentFilename);
    351                    string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
    352                    Connect(uri);//连接
    353                    reqFTP.Method = WebRequestMethods.Ftp.Rename;
    354                    reqFTP.RenameTo = newFilename;
    355                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    356                    response.Close();
    357    
    358                }
    359    
    360                catch (Exception ex)
    361                {
    362                    Log.WriteError("文件改名错误:" + ex.Message);
    363                }
    364    
    365            }
    366            //读取文件
    367    
    368            public Stream ReadFile(string fileName)
    369            {
    370                try
    371                {
    372                    string url = "ftp://" + ftpServerIP + "/" + fileName;
    373                    Connect(url);//连接
    374                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    375                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    376                    Stream ftpStream = response.GetResponseStream();
    377                    return ftpStream;
    378                }
    379    
    380                catch (Exception ex)
    381                {
    382                    Log.WriteError("读取文件错误:" + ex.Message);
    383                    return null;
    384                }
    385    
    386            }
    387    
    388            //获得文件明晰
    389    
    390            public string[] GetFilesDetailList()
    391            {
    392    
    393                return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
    394    
    395            }
    396    
    397            //获得文件明晰
    398    
    399            public string[] GetFilesDetailList(string path)
    400            {
    401    
    402                return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
    403    
    404            }
    405    
    406            // 文件存在检查
    407            public bool fileCheckExist(string fileName)
    408            {
    409                bool success = false;
    410                FtpWebResponse response = null;
    411                StreamReader reader = null;
    412                try
    413                {
    414                    string url = "ftp://" + ftpServerIP + "/" + fileName;
    415                    Connect(url);//连接
    416                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    417                    response = (FtpWebResponse)reqFTP.GetResponse();
    418                    reader = new StreamReader(response.GetResponseStream());
    419                    string line = reader.ReadLine();
    420                    if (line != null)
    421                    {
    422                        success = true;
    423                    }
    424                }
    425                catch (Exception)
    426                {
    427                    success = false;
    428                }
    429                finally
    430                {
    431                    if (reader != null)
    432                    {
    433                        reader.Close();
    434                    }
    435    
    436                    if (response != null)
    437                    {
    438                        response.Close();
    439                    }
    440                }
    441                return success;
    442            }
    443        }
    444    }
  • 相关阅读:
    嵌入式linux问题杂锦
    QT creator 调试问题
    torcs代码
    ubuntu12.04安装KDevelop
    ubuntu12.04LTS安装以及卸载 QT4.8.6和QT creator2.5.2
    用vs2010编译vs2013建的工程
    mysql+matlab配置
    流形学习笔记
    可用的rtmp互联网地址
    信用卡术语
  • 原文地址:https://www.cnblogs.com/weixing/p/2100639.html
Copyright © 2020-2023  润新知