C# Ftp操作工具類


參考一:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
 
using System.Globalization;
 
namespace FtpTest1
{
 
     public  class FtpWeb
    {
         string ftpServerIP;
         string ftpRemotePath;
         string ftpUserID;
         string ftpPassword;
         string ftpURI;
 
         ///   <summary>
        
///  連接FTP
        
///   </summary>
        
///   <param name="FtpServerIP"> FTP連接地址 </param>
        
///   <param name="FtpRemotePath"> 指定FTP連接成功后的當前目錄, 如果不指定即默認為根目錄 </param>
        
///   <param name="FtpUserID"> 用戶名 </param>
        
///   <param name="FtpPassword"> 密碼 </param>
         public FtpWeb( string FtpServerIP,  string FtpRemotePath,  string FtpUserID,  string FtpPassword)
        {
            ftpServerIP = FtpServerIP;
            ftpRemotePath = FtpRemotePath;
            ftpUserID = FtpUserID;
            ftpPassword = FtpPassword;
            ftpURI =  " ftp:// " + ftpServerIP +  " / " ;
        }
 
 
         static  void Main() {
             // string file = "c:\\aq3.gifa";
            
// FileInfo fileInf = new FileInfo(file);
            
// if (!fileInf.Exists)
            
// {
            
//     Console.WriteLine(file + " no exists");
            
// }
            
// else {
            
//     Console.WriteLine("yes");
            
// }
            
// Console.ReadLine();
            FtpWeb fw =  new FtpWeb( " 121.11.65.10 """" aa1 "" aa ");
             string[] filePaths = {  " c:\\aq3.gif1 "" c:\\aq2.gif1 "" c:\\bsmain_runtime.log " };
            Console.WriteLine(fw.UploadFile(filePaths));
            Console.ReadLine();
        }
 
         // 上傳文件
         public  string UploadFile(  string[] filePaths ) {
            StringBuilder sb =  new StringBuilder();
             if ( filePaths !=  null && filePaths.Length >  0 ){
                 foreachvar file  in filePaths ){
                    sb.Append(Upload( file ));
 
                }
            }
             return sb.ToString();
        }
 
          ///   <summary>
        
///  上傳文件
        
///   </summary>
        
///   <param name="filename"></param>
         private  string Upload( string filename)
        {
            FileInfo fileInf =  new FileInfo(filename);
             if ( !fileInf.Exists ){
                 return filename +  "  不存在!\n ";
            }
 
             string uri = ftpURI + fileInf.Name;
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri(uri));
 
            reqFTP.Credentials =  new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.KeepAlive =  false;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary =  true;
            reqFTP.UsePassive =  false;   // 選擇主動還是被動模式
            
// Entering Passive Mode
            reqFTP.ContentLength = fileInf.Length;
             int buffLength =  2048;
             byte[] buff =  new  byte[buffLength];
             int contentLen;
            FileStream fs = fileInf.OpenRead();
             try
            {
                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff,  0, buffLength);
                 while (contentLen !=  0)
                {
                    strm.Write(buff,  0, contentLen);
                    contentLen = fs.Read(buff,  0, buffLength);
                }
                strm.Close();
                fs.Close();
            }
             catch (Exception ex)
            {
                 return  " 同步  "+filename+ " 時連接不上服務器!\n ";
                 // Insert_Standard_ErrorLog.Insert("FtpWeb", "Upload Error --> " + ex.Message);
            }
             return  "";
        }
 
 
         ///   <summary>
        
///  下載
        
///   </summary>
        
///   <param name="filePath"></param>
        
///   <param name="fileName"></param>
         public  void Download( string filePath,  string fileName)
        {
            FtpWebRequest reqFTP;
             try
            {
                FileStream outputStream =  new FileStream(filePath +  " \\ " + fileName, FileMode.Create);
 
                reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri(ftpURI + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary =  true;
                reqFTP.Credentials =  new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                 long cl = response.ContentLength;
                 int bufferSize =  2048;
                 int readCount;
                 byte[] buffer =  new  byte[bufferSize];
 
                readCount = ftpStream.Read(buffer,  0, bufferSize);
                 while (readCount >  0)
                {
                    outputStream.Write(buffer,  0, readCount);
                    readCount = ftpStream.Read(buffer,  0, bufferSize);
                }
 
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
             catch (Exception ex)
            {
                Insert_Standard_ErrorLog.Insert( " FtpWeb "" Download Error -->  " + ex.Message);
            }
        }
 
         ///   <summary>
        
///  刪除文件
        
///   </summary>
        
///   <param name="fileName"></param>
         public  void Delete( string fileName)
        {
             try
            {
                 string uri = ftpURI + fileName;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri(uri));
 
                reqFTP.Credentials =  new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive =  false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
 
                 string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                 long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr =  new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
             catch (Exception ex)
            {
                Insert_Standard_ErrorLog.Insert( " FtpWeb "" Delete Error -->  " + ex.Message +  "   文件名: " + fileName);
            }
        }
 
         ///   <summary>
        
///  獲取當前目錄下明細(包含文件和文件夾)
        
///   </summary>
        
///   <returns></returns>
         public  string[] GetFilesDetailList()
        {
             string[] downloadFiles;
             try
            {
                StringBuilder result =  new StringBuilder();
                FtpWebRequest ftp;
                ftp = (FtpWebRequest)FtpWebRequest.Create( new Uri(ftpURI));
                ftp.Credentials =  new NetworkCredential(ftpUserID, ftpPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = ftp.GetResponse();
                StreamReader reader =  new StreamReader(response.GetResponseStream());
                 string line = reader.ReadLine();
                line = reader.ReadLine();
                line = reader.ReadLine();
                 while (line !=  null)
                {
                    result.Append(line);
                    result.Append( " \n ");
                    line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf( " \n "),  1);
                reader.Close();
                response.Close();
                 return result.ToString().Split( ' \n ');
            }
             catch (Exception ex)
            {
                downloadFiles =  null;
                Insert_Standard_ErrorLog.Insert( " FtpWeb "" GetFilesDetailList Error -->  " + ex.Message);
                 return downloadFiles;
            }
        }
 
         ///   <summary>
        
///  獲取當前目錄下文件列表(僅文件)
        
///   </summary>
        
///   <returns></returns>
         public  string[] GetFileList( string mask)
        {
             string[] downloadFiles;
            StringBuilder result =  new StringBuilder();
            FtpWebRequest reqFTP;
             try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri(ftpURI));
                reqFTP.UseBinary =  true;
                reqFTP.Credentials =  new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader =  new StreamReader(response.GetResponseStream());
 
                 string line = reader.ReadLine();
                 while (line !=  null)
                {
                     if (mask.Trim() !=  string.Empty && mask.Trim() !=  " *.* ")
                    {
                         string mask_ = mask.Substring( 0, mask.IndexOf( " * "));
                         if (line.Substring( 0, mask_.Length) == mask_)
                        {
                            result.Append(line);
                            result.Append( " \n ");
                        }
                    }
                     else
                    {
                        result.Append(line);
                        result.Append( " \n ");
                    }
                    line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf( ' \n '),  1);
                reader.Close();
                response.Close();
                 return result.ToString().Split( ' \n ');
            }
             catch (Exception ex)
            {
                downloadFiles =  null;
                 if (ex.Message.Trim() !=  " 遠程服務器返回錯誤: (550) 文件不可用(例如,未找到文件,無法訪問文件)。 ")
                {
                    Insert_Standard_ErrorLog.Insert( " FtpWeb "" GetFileList Error -->  " + ex.Message.ToString());
                }
                 return downloadFiles;
            }
        }
 
         ///   <summary>
        
///  獲取當前目錄下所有的文件夾列表(僅文件夾)
        
///   </summary>
        
///   <returns></returns>
         public  string[] GetDirectoryList()
        {
             string[] drectory = GetFilesDetailList();
             string m =  string.Empty;
             foreach ( string str  in drectory)
            {
                 if (str.Trim().Substring( 01).ToUpper() ==  " D ")
                {
                    m += str.Substring( 54).Trim() +  " \n ";
                }
            }
 
             char[] n =  new  char[] {  ' \n ' };
             return m.Split(n);
        }
 
         ///   <summary>
        
///  判斷當前目錄下指定的子目錄是否存在
        
///   </summary>
        
///   <param name="RemoteDirectoryName"> 指定的目錄名 </param>
         public  bool DirectoryExist( string RemoteDirectoryName)
        {
             string[] dirList = GetDirectoryList();
             foreach ( string str  in dirList)
            {
                 if (str.Trim() == RemoteDirectoryName.Trim())
                {
                     return  true;
                }
            }
             return  false;
        }
 
         ///   <summary>
        
///  判斷當前目錄下指定的文件是否存在
        
///   </summary>
        
///   <param name="RemoteFileName"> 遠程文件名 </param>
         public  bool FileExist( string RemoteFileName)
        {
             string[] fileList = GetFileList( " *.* ");
             foreach ( string str  in fileList)
            {
                 if (str.Trim() == RemoteFileName.Trim())
                {
                     return  true;
                }
            }
             return  false;
        }
 
         ///   <summary>
        
///  創建文件夾
        
///   </summary>
        
///   <param name="dirName"></param>
         public  void MakeDir( string dirName)
        {
            FtpWebRequest reqFTP;
             try
            {
                 //  dirName = name of the directory to create.
                reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri(ftpURI + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary =  true;
                reqFTP.Credentials =  new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
 
                ftpStream.Close();
                response.Close();
            }
             catch (Exception ex)
            {
                Insert_Standard_ErrorLog.Insert( " FtpWeb "" MakeDir Error -->  " + ex.Message);
            }
        }
 
         ///   <summary>
        
///  獲取指定文件大小
        
///   </summary>
        
///   <param name="filename"></param>
        
///   <returns></returns>
         public  long GetFileSize( string filename)
        {
            FtpWebRequest reqFTP;
             long fileSize =  0;
             try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri(ftpURI + filename));
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary =  true;
                reqFTP.Credentials =  new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;
 
                ftpStream.Close();
                response.Close();
            }
             catch (Exception ex)
            {
                Insert_Standard_ErrorLog.Insert( " FtpWeb "" GetFileSize Error -->  " + ex.Message);
            }
             return fileSize;
        }
 
         ///   <summary>
        
///  改名
        
///   </summary>
        
///   <param name="currentFilename"></param>
        
///   <param name="newFilename"></param>
         public  void ReName( string currentFilename,  string newFilename)
        {
            FtpWebRequest reqFTP;
             try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri(ftpURI + currentFilename));
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newFilename;
                reqFTP.UseBinary =  true;
                reqFTP.Credentials =  new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
 
                ftpStream.Close();
                response.Close();
            }
             catch (Exception ex)
            {
                Insert_Standard_ErrorLog.Insert( " FtpWeb "" ReName Error -->  " + ex.Message);
            }
        }
 
         ///   <summary>
        
///  移動文件
        
///   </summary>
        
///   <param name="currentFilename"></param>
        
///   <param name="newFilename"></param>
         public  void MovieFile( string currentFilename,  string newDirectory)
        {
            ReName(currentFilename, newDirectory);
        }
參考二:
using System.IO;
using System.Net;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;

     // 從ftp上下載文件
     private  void Download( string filePath,  string ImageSrc,  string ImageName,  string ftpServerIP,  string 
 

ftpUserName,  string ftpPwd)
    {
         if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }
         using (FileStream OutputStream =  new FileStream(filePath +  " \\ " + ImageName, FileMode.Create))
        {
            FtpWebRequest ReqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri( " ftp:// " + ftpServerIP +  " / " + 

ImageSrc));

            ReqFTP.Method = WebRequestMethods.Ftp.DownloadFile;

            ReqFTP.UseBinary =  true;

            ReqFTP.Credentials =  new NetworkCredential(ftpUserName, ftpPwd);

             using (FtpWebResponse response = (FtpWebResponse)ReqFTP.GetResponse())
            {

                 using (Stream FtpStream = response.GetResponseStream())
                {

                     long Cl = response.ContentLength;

                     int bufferSize =  2048;

                     int readCount;

                     byte[] buffer =  new  byte[bufferSize];

                    readCount = FtpStream.Read(buffer,  0, bufferSize);

                     while (readCount >  0)
                    {
                        OutputStream.Write(buffer,  0, readCount);

                        readCount = FtpStream.Read(buffer,  0, bufferSize);
                    }

                    FtpStream.Close();
                }

                response.Close();

            }

            OutputStream.Close();
        }

    }
         // 從服務器上傳文件到FTP上
     private  void UploadSmall( string sFileDstPath,  string FolderName,  string ftpServerIP,  string ftpUserName, 

string ftpPwd)
    {

        FileInfo fileInf =  new FileInfo(sFileDstPath);

        FtpWebRequest reqFTP;

        reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri( " ftp:// " + ftpServerIP +  " / " + FolderName +  " / " + 

fileInf.Name));

        reqFTP.Credentials =  new NetworkCredential(ftpUserName, ftpPwd);

        reqFTP.KeepAlive =  false;

        reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

        reqFTP.UseBinary =  true;

        reqFTP.ContentLength = fileInf.Length;

         int buffLength =  2048;

         byte[] buff =  new  byte[buffLength];

         int contentLen;

         using (FileStream fs = fileInf.OpenRead())
        {

             using (Stream strm = reqFTP.GetRequestStream())
            {

                contentLen = fs.Read(buff,  0, buffLength);

                 while (contentLen !=  0)
                {

                    strm.Write(buff,  0, contentLen);

                    contentLen = fs.Read(buff,  0, buffLength);
                }

                strm.Close();
            }

            fs.Close();
        }

    }
     // 刪除服務器上的文件
     private  void DeleteWebServerFile( string sFilePath)
    {
         if (File.Exists(sFilePath))
        {
            File.Delete(sFilePath);
        }
    }
     // 刪除FTP上的文件
     private  void DeleteFtpFile( string[] IName,  string FolderName,  string ftpServerIP,  string ftpUserName,  string 

ftpPwd)
    {
         foreach ( string ImageName  in IName)
        {
             string[] FileList = GetFileList(FolderName, ftpServerIP, ftpUserName, ftpPwd);
             for ( int i =  0; i < FileList.Length; i++)
            {
                 string Name = FileList[i].ToString();
                 if (Name == ImageName)
                {
                    FtpWebRequest ReqFTP;

                    ReqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri( " ftp:// " + ftpServerIP +  " / " + 

FolderName +  " / " + ImageName));

                    ReqFTP.Credentials =  new NetworkCredential(ftpUserName, ftpPwd);

                    ReqFTP.KeepAlive =  false;

                    ReqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

                    ReqFTP.UseBinary =  true;

                     using (FtpWebResponse Response = (FtpWebResponse)ReqFTP.GetResponse())
                    {

                         long size = Response.ContentLength;

                         using (Stream datastream = Response.GetResponseStream())
                        {

                             using (StreamReader sr =  new StreamReader(datastream))
                            {

                                sr.ReadToEnd();

                                sr.Close();
                            }

                            datastream.Close();
                        }

                        Response.Close();
                    }
                }
            }

        }

    }
     // 檢查文件是否存在
     public  string[] GetFileList( string FolderName,  string ftpServerIP,  string ftpUserName,  string ftpPwd)
    {
         string[] downloadFiles;

        StringBuilder result =  new StringBuilder();

        FtpWebRequest reqFTP;
         try
        {
            reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri( " ftp:// " + ftpServerIP +  " / " + FolderName + 

" / "));

            reqFTP.UseBinary =  true;

            reqFTP.Credentials =  new NetworkCredential(ftpUserName, ftpPwd);

            reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;

            WebResponse response = reqFTP.GetResponse();

            StreamReader reader =  new StreamReader(response.GetResponseStream());

             string line = reader.ReadLine();

             while (line !=  null)
            {
                result.Append(line);

                result.Append( " \n ");

                line = reader.ReadLine();
            }
             //  to remove the trailing '\n'        
            result.Remove(result.ToString().LastIndexOf( ' \n '),  1);

            reader.Close();

            response.Close();

             return result.ToString().Split( ' \n ');
        }
         catch (Exception ex)
        {
            downloadFiles =  null;
             return downloadFiles;
        }
    }
     // 從客戶端上傳文件到FTP上
     private  void UploadFtp(HttpPostedFile sFilePath,  string filename,  string FolderName,  string ftpServerIP, 

string ftpUserName,  string ftpPwd)
    {
         // 獲取的服務器路徑
        
// FileInfo fileInf = new FileInfo(sFilePath);

        FtpWebRequest reqFTP;

        reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri( " ftp:// " + ftpServerIP +  " / " + FolderName +  " / " + 

filename));

        reqFTP.Credentials =  new NetworkCredential(ftpUserName, ftpPwd);

        reqFTP.KeepAlive =  false;

        reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

        reqFTP.UseBinary =  true;

        reqFTP.ContentLength = sFilePath.ContentLength;
         // 設置緩存
         int buffLength =  2048;

         byte[] buff =  new  byte[buffLength];

         int contentLen;

         using (Stream fs = sFilePath.InputStream)
        {

             using (Stream strm = reqFTP.GetRequestStream())
            {

                contentLen = fs.Read(buff,  0, buffLength);

                 while (contentLen !=  0)
                {

                    strm.Write(buff,  0, contentLen);

                    contentLen = fs.Read(buff,  0, buffLength);
                }

                strm.Close();
            }

            fs.Close();
        }

    }
     // 創建目錄
     private  void CreateDirectory( string FolderName,  string ftpServerIP,  string ftpUserName,  string ftpPwd)
    {
         // 創建日期目錄
         try
        {
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri( " ftp:// " + ftpServerIP +  " / " + 

FolderName));

            reqFTP.UseBinary =  true;

            reqFTP.Credentials =  new NetworkCredential(ftpUserName, ftpPwd);

            reqFTP.KeepAlive =  false;

            reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;

            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
        }
         catch
        {
            ClientScript.RegisterStartupScript( this.GetType(),  """ <script>alert('系統忙,請稍后再

試! ' );location.href=location.href;</script>");
        }
    }
     // 檢查日期目錄和文件是否存在
     private  static Regex regexName =  new Regex( @" [^\s]*$ ", RegexOptions.Compiled);
     private  bool CheckFileOrPath( string FolderName,  string ftpServerIP,  string ftpUserName,  string ftpPwd)
    {
         // 檢查一下日期目錄是否存在
        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create( new Uri( " ftp:// " + ftpServerIP +  " / "));

        reqFTP.UseBinary =  true;

        reqFTP.Credentials =  new NetworkCredential(ftpUserName, ftpPwd);

        reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

        Stream stream = reqFTP.GetResponse().GetResponseStream();

         using (StreamReader sr =  new StreamReader(stream))
        {
             string line = sr.ReadLine();

             while (! string.IsNullOrEmpty(line))
            {
                GroupCollection gc = regexName.Match(line).Groups;
                 if (gc.Count !=  1)
                {
                     throw  new ApplicationException( " FTP 返回的字串格式不正確 ");
                }

                 string path = gc[ 0].Value;
                 if (path == FolderName)
                {
                     return  true;
                }

                line = sr.ReadLine();
            }
        }

         return  false;

    }
}


 
url: http://greatverve.cnblogs.com/archive/2012/03/02/csharp-ftp.html
參考三:
using  System;
using  System.Net;
using  System.IO;
using  System.Text;
using  System.Net.Sockets;

///  <summary>
///  FTPClient 的摘要說明。
///  </summary>
public  class  FTPClient

    
#region  構造函數
///  <summary>
///  缺省構造函數
///  </summary>
public  FTPClient()
{
   strRemoteHost 
=  "" ;
   strRemotePath 
=  "" ;
   strRemoteUser 
=  "" ;
   strRemotePass 
=  "" ;
   strRemotePort 
=  21 ;
   bConnected     
=  false ;
///  <summary>
///  構造函數
///  </summary>
///  <param name="remoteHost"></param>
///  <param name="remotePath"></param>
///  <param name="remoteUser"></param>
///  <param name="remotePass"></param>
///  <param name="remotePort"></param>
public  FTPClient( string  remoteHost,  string  remotePath,  string  remoteUser,  string  remotePass,  int  remotePort )
{
   strRemoteHost 
=  remoteHost;
   strRemotePath 
=  remotePath;
   strRemoteUser 
=  remoteUser;
   strRemotePass 
=  remotePass;
   strRemotePort 
=  remotePort;
   Connect();
}
#endregion 
    
#region  登陸
///  <summary>
///  FTP服務器IP地址
///  </summary>
private  string  strRemoteHost;
public  string  RemoteHost
{
   
get
   {
    
return  strRemoteHost;
   }
   
set
   {
    strRemoteHost 
=  value;
   }
}
///  <summary>
///  FTP服務器端口
///  </summary>
private  int  strRemotePort;
public  int  RemotePort
{
   
get
   {
    
return  strRemotePort;
   }
   
set
   {
    strRemotePort 
=  value;
   }
}
///  <summary>
///  當前服務器目錄
///  </summary>
private  string  strRemotePath;
public  string  RemotePath
{
   
get
   {
    
return  strRemotePath;
   }
   
set
   {
    strRemotePath 
=  value;
   }
}
///  <summary>
///  登錄用戶賬號
///  </summary>
private  string  strRemoteUser;
public  string  RemoteUser
{
   
set
   {
    strRemoteUser 
=  value;
   }
}
///  <summary>
///  用戶登錄密碼
///  </summary>
private  string  strRemotePass;
public  string  RemotePass
{
   
set
   {
    strRemotePass 
=  value;
   }
///  <summary>
///  是否登錄
///  </summary>
private  Boolean bConnected;
public  bool  Connected
{
   
get
   {
    
return  bConnected;
   }
}
#endregion 
    
#region  鏈接
///  <summary>
///  建立連接 
///  </summary>
public  void  Connect()
{
   socketControl 
=  new  Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
   IPEndPoint ep 
=  new  IPEndPoint(IPAddress.Parse(RemoteHost), strRemotePort);
   
//  鏈接
    try
   {
    socketControl.Connect(ep);
   }
   
catch (Exception)
   {
    
throw  new  IOException( " Couldn't connect to remote server " );
   }   
//  獲取應答碼
   ReadReply();
   
if (iReplyCode  !=  220 )
   {
    DisConnect();
    
throw  new  IOException(strReply.Substring( 4 ));
   }   
//  登陸
   SendCommand( " USER  " + strRemoteUser);
   
if ! (iReplyCode  ==  331  ||  iReplyCode  ==  230 ) )
   {
    CloseSocketConnect();
// 關閉連接
     throw  new  IOException(strReply.Substring( 4 ));
   }
   
if ( iReplyCode  !=  230  )
   {
    SendCommand(
" PASS  " + strRemotePass);
    
if ! (iReplyCode  ==  230  ||  iReplyCode  ==  202 ) )
    {
     CloseSocketConnect();
// 關閉連接
      throw  new  IOException(strReply.Substring( 4 ));
    }
   }
   bConnected 
=  true ;    //  切換到目錄
   ChDir(strRemotePath);
}
      
///  <summary>
///  關閉連接
///  </summary>
public  void  DisConnect()
{
   
if ( socketControl  !=  null  )
   {
    SendCommand(
" QUIT " );
   }
   CloseSocketConnect();

    
#endregion 
    
#region  傳輸模式  // / <summary>
///  傳輸模式:二進制類型、ASCII類型
///  </summary>
public  enum  TransferType {Binary,ASCII};  ///  <summary>
///  設置傳輸模式
///  </summary>
///  <param name="ttType"> 傳輸模式 </param>
public  void  SetTransferType(TransferType ttType)
{
   
if (ttType  ==  TransferType.Binary)
   {
    SendCommand(
" TYPE I " ); // binary類型傳輸
   }
   
else
   {
    SendCommand(
" TYPE A " ); // ASCII類型傳輸
   }
   
if  (iReplyCode  !=  200 )
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }
   
else
   {
    trType 
=  ttType;
   }
}
///  <summary>
///  獲得傳輸模式
///  </summary>
///  <returns> 傳輸模式 </returns>
public  TransferType GetTransferType()
{
   
return  trType;
}
    
#endregion 
    
#region  文件操作
///  <summary>
///  獲得文件列表
///  </summary>
///  <param name="strMask"> 文件名的匹配字符串 </param>
///  <returns></returns>
public  string [] Dir( string  strMask)
{
   
//  建立鏈接
    if ( ! bConnected)
   {
    Connect();
   }   
// 建立進行數據連接的socket
   Socket socketData  =  CreateDataSocket();
   
   
// 傳送命令
   SendCommand( " NLST  "  +  strMask);    // 分析應答代碼
    if ( ! (iReplyCode  ==  150  ||  iReplyCode  ==  125  ||  iReplyCode  ==  226 ))
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }   
// 獲得結果
   strMsg  =  "" ;
   
while ( true )
   {
    
int  iBytes  =  socketData.Receive(buffer, buffer.Length,  0 );
    strMsg 
+=  ASCII.GetString(buffer,  0 , iBytes);
    
if (iBytes  <  buffer.Length)
    {
     
break ;
    }
   }
   
char [] seperator  =  { ' \n ' };
   
string [] strsFileList  =  strMsg.Split(seperator);
   socketData.Close();
// 數據socket關閉時也會有返回碼
    if (iReplyCode  !=  226 )
   {
    ReadReply();
    
if (iReplyCode  !=  226 )
    {
     
throw  new  IOException(strReply.Substring( 4 ));
    }
   }
   
return  strsFileList;
}
      
///  <summary>
///  獲取文件大小
///  </summary>
///  <param name="strFileName"> 文件名 </param>
///  <returns> 文件大小 </returns>
private  long  GetFileSize( string  strFileName)
{
   
if ( ! bConnected)
   {
    Connect();
   }
   SendCommand(
" SIZE  "  +  Path.GetFileName(strFileName));
   
long  lSize = 0 ;
   
if (iReplyCode  ==  213 )
   {
    lSize 
=  Int64.Parse(strReply.Substring( 4 ));
   }
   
else
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }
   
return  lSize;
}
///  <summary>
///  刪除
///  </summary>
///  <param name="strFileName"> 待刪除文件名 </param>
public  void  Delete( string  strFileName)
{
   
if ( ! bConnected)
   {
    Connect();
   }
   SendCommand(
" DELE  " + strFileName);
   
if (iReplyCode  !=  250 )
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }
}
      
///  <summary>
///  重命名(如果新文件名與已有文件重名,將覆蓋已有文件)
///  </summary>
///  <param name="strOldFileName"> 舊文件名 </param>
///  <param name="strNewFileName"> 新文件名 </param>
public  void  Rename( string  strOldFileName, string  strNewFileName)
{
   
if ( ! bConnected)
   {
    Connect();
   }
   SendCommand(
" RNFR  " + strOldFileName);
   
if (iReplyCode  !=  350 )
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }
   
//  如果新文件名與原有文件重名,將覆蓋原有文件
   SendCommand( " RNTO  " + strNewFileName);
   
if (iReplyCode  !=  250 )
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }
}
#endregion 
    
#region  上傳和下載
///  <summary>
///  下載一批文件
///  </summary>
///  <param name="strFileNameMask"> 文件名的匹配字符串 </param>
///  <param name="strFolder"> 本地目錄(不得以\結束) </param>
public  void  Get( string  strFileNameMask, string  strFolder)
{
   
if ( ! bConnected)
   {
    Connect();
   }
   
string [] strFiles  =  Dir(strFileNameMask);
   
foreach ( string  strFile  in  strFiles)
   {
    
if ( ! strFile.Equals( "" )) // 一般來說strFiles的最后一個元素可能是空字符串
    {
     Get(strFile,strFolder,strFile);
    }
   }
}
      
///  <summary>
///  下載一個文件
///  </summary>
///  <param name="strRemoteFileName"> 要下載的文件名 </param>
///  <param name="strFolder"> 本地目錄(不得以\結束) </param>
///  <param name="strLocalFileName"> 保存在本地時的文件名 </param>
public  void  Get( string  strRemoteFileName, string  strFolder, string  strLocalFileName)
{
   
if ( ! bConnected)
   {
    Connect();
   }
   SetTransferType(TransferType.Binary);
   
if  (strLocalFileName.Equals( "" ))
   {
    strLocalFileName 
=  strRemoteFileName;
   }
   
if ( ! File.Exists(strLocalFileName))
   {
    Stream st 
=  File.Create(strLocalFileName);
    st.Close();
   }
   FileStream output 
=  new  
    FileStream(strFolder 
+  " \\ "  +  strLocalFileName,FileMode.Create);
   Socket socketData 
=  CreateDataSocket();
   SendCommand(
" RETR  "  +  strRemoteFileName);
   
if ( ! (iReplyCode  ==  150  ||  iReplyCode  ==  125
    
||  iReplyCode  ==  226  ||  iReplyCode  ==  250 ))
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }
   
while ( true )
   {
    
int  iBytes  =  socketData.Receive(buffer, buffer.Length,  0 );
    output.Write(buffer,
0 ,iBytes);
    
if (iBytes  <=  0 )
    {
     
break ;
    }
   }
   output.Close();
   
if  (socketData.Connected)
   {
    socketData.Close();
   }
   
if ( ! (iReplyCode  ==  226  ||  iReplyCode  ==  250 ))
   {
    ReadReply();
    
if ( ! (iReplyCode  ==  226  ||  iReplyCode  ==  250 ))
    {
     
throw  new  IOException(strReply.Substring( 4 ));
    }
   }
}
      
///  <summary>
///  上傳一批文件
///  </summary>
///  <param name="strFolder"> 本地目錄(不得以\結束) </param>
///  <param name="strFileNameMask"> 文件名匹配字符(可以包含*和?) </param>
public  void  Put( string  strFolder, string  strFileNameMask)
{
   
string [] strFiles  =  Directory.GetFiles(strFolder,strFileNameMask);
   
foreach ( string  strFile  in  strFiles)
   {
    
// strFile是完整的文件名(包含路徑)
    Put(strFile);
   }
}
      
///  <summary>
///  上傳一個文件
///  </summary>
///  <param name="strFileName"> 本地文件名 </param>
public  void  Put( string  strFileName)
{
   
if ( ! bConnected)
   {
    Connect();
   }
   Socket socketData 
=  CreateDataSocket();
   SendCommand(
" STOR  " + Path.GetFileName(strFileName));
   
if ! (iReplyCode  ==  125  ||  iReplyCode  ==  150 ) )
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }
   FileStream input 
=  new  
    FileStream(strFileName,FileMode.Open);
   
int  iBytes  =  0 ;
   
while  ((iBytes  =  input.Read(buffer, 0 ,buffer.Length))  >  0 )
   {
    socketData.Send(buffer, iBytes, 
0 );
   }
   input.Close();
   
if  (socketData.Connected)
   {
    socketData.Close();
   }
   
if ( ! (iReplyCode  ==  226  ||  iReplyCode  ==  250 ))
   {
    ReadReply();
    
if ( ! (iReplyCode  ==  226  ||  iReplyCode  ==  250 ))
    {
     
throw  new  IOException(strReply.Substring( 4 ));
    }
   }
}
    
#endregion 
    
#region  目錄操作
///  <summary>
///  創建目錄
///  </summary>
///  <param name="strDirName"> 目錄名 </param>
public  void  MkDir( string  strDirName)
{
   
if ( ! bConnected)
   {
    Connect();
   }
   SendCommand(
" MKD  " + strDirName);
   
if (iReplyCode  !=  257 )
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }
}
    

///  <summary>
///  刪除目錄
///  </summary>
///  <param name="strDirName"> 目錄名 </param>
public  void  RmDir( string  strDirName)
{
   
if ( ! bConnected)
   {
    Connect();
   }
   SendCommand(
" RMD  " + strDirName);
   
if (iReplyCode  !=  250 )
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }
}
    

///  <summary>
///  改變目錄
///  </summary>
///  <param name="strDirName"> 新的工作目錄名 </param>
public  void  ChDir( string  strDirName)
{
   
if (strDirName.Equals( " . " ||  strDirName.Equals( "" ))
   {
    
return ;
   }
   
if ( ! bConnected)
   {
    Connect();
   }
   SendCommand(
" CWD  " + strDirName);
   
if (iReplyCode  !=  250 )
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }
   
this .strRemotePath  =  strDirName;
}
    
#endregion 
    
#region  內部變量
///  <summary>
///  服務器返回的應答信息(包含應答碼)
///  </summary>
private  string  strMsg;
///  <summary>
///  服務器返回的應答信息(包含應答碼)
///  </summary>
private  string  strReply;
///  <summary>
///  服務器返回的應答碼
///  </summary>
private  int  iReplyCode;
///  <summary>
///  進行控制連接的socket
///  </summary>
private  Socket socketControl;
///  <summary>
///  傳輸模式
///  </summary>
private  TransferType trType;
///  <summary>
///  接收和發送數據的緩沖區
///  </summary>
private  static  int  BLOCK_SIZE  =  512 ;
Byte[] buffer 
=  new  Byte[BLOCK_SIZE];
///  <summary>
///  編碼方式
///  </summary>
Encoding ASCII  =  Encoding.ASCII;
#endregion 
    
#region  內部函數
///  <summary>
///  將一行應答字符串記錄在strReply和strMsg
///  應答碼記錄在iReplyCode
///  </summary>
private  void  ReadReply()
{
   strMsg 
=  "" ;
   strReply 
=  ReadLine();
   iReplyCode 
=  Int32.Parse(strReply.Substring( 0 , 3 ));
///  <summary>
///  建立進行數據連接的socket
///  </summary>
///  <returns> 數據連接socket </returns>
private  Socket CreateDataSocket()
{
   SendCommand(
" PASV " );
   
if (iReplyCode  !=  227 )
   {
    
throw  new  IOException(strReply.Substring( 4 ));
   }
   
int  index1  =  strReply.IndexOf( ' ( ' );
   
int  index2  =  strReply.IndexOf( ' ) ' );
   
string  ipData  =  
    strReply.Substring(index1
+ 1 ,index2 - index1 - 1 );
   
int [] parts  =  new  int [ 6 ];
   
int  len  =  ipData.Length;
   
int  partCount  =  0 ;
   
string  buf = "" ;
   
for  ( int  i  =  0 ; i  <  len  &&  partCount  <=  6 ; i ++ )
   {
    
char  ch  =  Char.Parse(ipData.Substring(i, 1 ));
    
if  (Char.IsDigit(ch))
     buf
+= ch;
    
else  if  (ch  !=  ' , ' )
    {
     
throw  new  IOException( " Malformed PASV strReply:  "  +  
      strReply);
    }
    
if  (ch  ==  ' , '  ||  i + 1  ==  len)
    {
     
try
     {
      parts[partCount
++ =  Int32.Parse(buf);
      buf
= "" ;
     }
     
catch  (Exception)
     {
      
throw  new  IOException( " Malformed PASV strReply:  "  +  
       strReply);
     }
    }
   }
   
string  ipAddress  =  parts[ 0 +  " . " +  parts[ 1 ] +  " . "  +
    parts[
2 +  " . "  +  parts[ 3 ];
   
int  port  =  (parts[ 4 <<  8 +  parts[ 5 ];
   Socket s 
=  new  
    Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
   IPEndPoint ep 
=  new  
    IPEndPoint(IPAddress.Parse(ipAddress), port);
   
try
   {
    s.Connect(ep);
   }
   
catch (Exception)
   {
    
throw  new  IOException( " Can't connect to remote server " );
   }
   
return  s;
}
///  <summary>
///  關閉socket連接(用於登錄以前)
///  </summary>
private  void  CloseSocketConnect()
{
   
if (socketControl != null )
   {
    socketControl.Close();
    socketControl 
=  null ;
   }
   bConnected 
=  false ;
}

///  <summary>
///  讀取Socket返回的所有字符串
///  </summary>
///  <returns> 包含應答碼的字符串行 </returns>
private  string  ReadLine()
{
   
while ( true )
   {
    
int  iBytes  =  socketControl.Receive(buffer, buffer.Length,  0 );
    strMsg 
+=  ASCII.GetString(buffer,  0 , iBytes);
    
if (iBytes  <  buffer.Length)
    {
     
break ;
    }
   }
   
char [] seperator  =  { ' \n ' };
   
string [] mess  =  strMsg.Split(seperator);
   
if (strMsg.Length  >  2 )
   {
    strMsg 
=  mess[mess.Length - 2 ];
    
// seperator[0]是10,換行符是由13和0組成的,分隔后10后面雖沒有字符串,
    
// 但也會分配為空字符串給后面(也是最后一個)字符串數組,
    
// 所以最后一個mess是沒用的空字符串
    
// 但為什么不直接取mess[0],因為只有最后一行字符串應答碼與信息之間有空格
   }
   
else
   {
    strMsg 
=  mess[ 0 ];
   }
   
if ( ! strMsg.Substring( 3 , 1 ).Equals( "  " )) // 返回字符串正確的是以應答碼(如220開頭,后面接一空格,再接問候字符串)
   {
    
return  ReadLine();
   }
   
return  strMsg;
}
///  <summary>
///  發送命令並獲取應答碼和最后一行應答字符串
///  </summary>
///  <param name="strCommand"> 命令 </param>
private  void  SendCommand(String strCommand)
{
            
// Byte[] cmdBytes =
            
//  Encoding.ASCII.GetBytes((strCommand + "\r\n").ToCharArray());
             byte [] cmdBytes  =  Encoding.GetEncoding( " gb2312 " ).GetBytes((strCommand  +  " \r\n " ).ToCharArray());
            socketControl.Send(cmdBytes, cmdBytes.Length, 
0 );
            ReadReply();

    
#endregion 
}
url:
.net 2.0(c#)下簡單的FTP應用程序
原文地址: http://www.c-sharpcorner.com/UploadFile/neo_matrix/SimpleFTP01172007082222AM/SimpleFTP.aspx
[原文源碼下載]

原文發布日期:2007.01.18
作者: Neo Matrix
翻譯: webabcd

本文使用.net 2.0(c#)來實現一般的FTP功能

介紹
微軟的.net framework 2.0相對於1.x來說增加了對FTP的支持。以前為了符合我的需求,我不等不使用第三方類庫來實現FTP功能,但是為了可靠,還是使用.net framework的類比較好。我的這段代碼沒有做成可重復使用的類庫的形式,但它卻是比較容易理解的並能滿足你的需求。它可以實現上傳,下載,刪除等任意功能。在這篇文章的后面將給大家出示.net 2.0下實現ftp的簡單代碼,使用的語言是c#。或許是因為這是.net新增的類,又或許是第三方類庫已經能很好的實現你的需求,.net 2.0的這部分類庫並沒有得到足夠的關注。

背景
作為我的工作的一部分,我已經使用了ftp模塊,但是我只能在.net 1.1中去使用它,所以我不能深入的研究.net 2.0下ftp的實現。但是我相信,.ne 2.0下對ftp的支持是非常好的。

代碼
不要忘記引入命名空間
using System.Net;
using System.IO;

下面的幾個步驟包括了使用FtpWebRequest類實現ftp功能的一般過程

1、創建一個FtpWebRequest對象,指向ftp服務器的uri
2、設置ftp的執行方法(上傳,下載等)
3、給FtpWebRequest對象設置屬性(是否支持ssl,是否使用二進制傳輸等)
4、設置登錄驗證(用戶名,密碼)
5、執行請求
6、接收相應流(如果需要的話)
7、如果沒有打開的流,則關閉ftp請求

開發任何ftp應用程序都需要一個相關的ftp服務器及它的配置信息。FtpWebRequest暴露了一些屬性來設置這些信息。

接下來的代碼示例了上傳功能

首先設置一個uri地址,包括路徑和文件名。這個uri被使用在FtpWebRequest實例中。

然后根據ftp請求設置FtpWebRequest對象的屬性

其中一些重要的屬性如下:
    ·Credentials - 指定登錄ftp服務器的用戶名和密碼。
    ·KeepAlive - 指定連接是應該關閉還是在請求完成之后關閉,默認為true
    ·UseBinary - 指定文件傳輸的類型。有兩種文件傳輸模式,一種是Binary,另一種是ASCII。兩種方法在傳輸時,字節的第8位是不同的。ASCII使用第8位作為錯誤控制,而Binary的8位都是有意義的。所以當你使用ASCII傳輸時要小心一些。簡單的說,如果能用記事本讀和寫的文件用ASCII傳輸就是安全的,而其他的則必須使用Binary模式。當然使用Binary模式發送ASCII文件也是非常好的。
    ·UsePassive - 指定使用主動模式還是被動模式。早先所有客戶端都使用主動模式,而且工作的很好,而現在因為客戶端防火牆的存在,將會關閉一些端口,這樣主動模式將會失敗。在這種情況下就要使用被動模式,但是一些端口也可能被服務器的防火牆封掉。不過因為ftp服務器需要它的ftp服務連接到一定數量的客戶端,所以他們總是支持被動模式的。這就是我們為什么要使用被動模式的原意,為了確保數據可以正確的傳輸,使用被動模式要明顯優於主動模式。(譯者注:主動(PORT)模式建立數據傳輸通道是由服務器端發起的,服務器使用20端口連接客戶端的某一個大於1024的端口;在被動(PASV)模式中,數據傳輸的通道的建立是由FTP客戶端發起的,他使用一個大於1024的端口連接服務器的1024以上的某一個端口)
    ·ContentLength - 設置這個屬性對於ftp服務器是有用的,但是客戶端不使用它,因為FtpWebRequest忽略這個屬性,所以在這種情況下,該屬性是無效的。但是如果我們設置了這個屬性,ftp服務器將會提前預知文件的大小(在upload時會有這種情況)
    ·Method - 指定當前請求是什么命令(upload,download,filelist等)。這個值定義在結構體WebRequestMethods.Ftp中。

private  void Upload( string filename)
{
    FileInfo fileInf = new FileInfo(filename);
    string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
    FtpWebRequest reqFTP; 

    // 根據uri創建FtpWebRequest對象 
    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name)); 

    // ftp用戶名和密碼
    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 

    // 默認為true,連接不會被關閉
    
// 在一個命令之后被執行
    reqFTP.KeepAlive = false

    // 指定執行什么命令
    reqFTP.Method = WebRequestMethods.Ftp.UploadFile; 

    // 指定數據傳輸類型
    reqFTP.UseBinary = true

    // 上傳文件時通知服務器文件的大小
    reqFTP.ContentLength = fileInf.Length; 

    // 緩沖大小設置為2kb
    int buffLength = 2048;

    byte[] buff = new byte[buffLength];
    int contentLen; 

    // 打開一個文件流 (System.IO.FileStream) 去讀上傳的文件
    FileStream fs = fileInf.OpenRead(); 
    try
    {
        // 把上傳的文件寫入流
        Stream strm = reqFTP.GetRequestStream(); 

        // 每次讀文件流的2kb
        contentLen = fs.Read(buff, 0, buffLength); 

        // 流內容沒有結束
        while (contentLen != 0)
        {
            // 把內容從file stream 寫入 upload stream
            strm.Write(buff, 0, contentLen);

            contentLen = fs.Read(buff, 0, buffLength);
        }
 

        // 關閉兩個流
        strm.Close();
        fs.Close();
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Upload Error");
    }

}

以上代碼簡單的示例了ftp的上傳功能。創建一個指向某ftp服務器的FtpWebRequest對象,然后設置其不同的屬性Credentials,KeepAlive,Method,UseBinary,ContentLength。

打開本地機器上的文件,把其內容寫入ftp請求流。緩沖的大小為2kb,無論上傳大文件還是小文件,這都是一個合適的大小。

private  void Download( string filePath,  string fileName)
{
    FtpWebRequest reqFTP;

    try
    {
        FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create); 

        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));

        reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;

        reqFTP.UseBinary = true;

        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

        Stream ftpStream = response.GetResponseStream();

        long cl = response.ContentLength;

        int bufferSize = 2048;

        int readCount;

        byte[] buffer = new byte[bufferSize];

        readCount = ftpStream.Read(buffer, 0, bufferSize);

        while (readCount > 0)
        {
            outputStream.Write(buffer, 0, readCount);

            readCount = ftpStream.Read(buffer, 0, bufferSize);
        }


        ftpStream.Close();

        outputStream.Close();

        response.Close();
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

}

上面的代碼實現了從ftp服務器上下載文件的功能。這不同於之前所提到的上傳功能,下載需要一個響應流,它包含着下載文件的內容。這個下載的文件是在FtpWebRequest對象中的uri指定的。在得到所請求的文件后,通過FtpWebRequest對象的GetResponse()方法下載文件。它將把文件作為一個流下載到你的客戶端的機器上。

注意:我們可以設置文件在我們本地機器上的存放路徑和名稱。

public  string[] GetFileList()
{    
    string[] downloadFiles;    
    StringBuilder result = new StringBuilder();    
    FtpWebRequest reqFTP;    
    try    
    {        
        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));        
        reqFTP.UseBinary = true;        
        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);        
        reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;        
        WebResponse response = reqFTP.GetResponse();        
        StreamReader reader = new StreamReader(response.GetResponseStream());        
        string line = reader.ReadLine();        
        while (line != null)        
        {            
            result.Append(line);            
            result.Append("\n");            
            line = reader.ReadLine();        
        }
        
        // to remove the trailing '\n'        
        result.Remove(result.ToString().LastIndexOf('\n'), 1);        
        reader.Close();        
        response.Close();        
        return result.ToString().Split('\n');    
    }
    
    catch (Exception ex)    
    {        
        System.Windows.Forms.MessageBox.Show(ex.Message);        
        downloadFiles = null;        
        return downloadFiles;    
    }

}

上面的代碼示例了如何從ftp服務器上獲得文件列表。uri指向ftp服務器的地址。我們使用StreamReader對象來存儲一個流,文件名稱列表通過“\r\n”分隔開,也就是說每一個文件名稱都占一行。你可以使用StreamReader對象的ReadToEnd()方法來得到文件列表。上面的代碼中我們用一個StringBuilder對象來保存文件名稱,然后把結果通過分隔符分開后作為一個數組返回。我確定只是一個比較好的方法。

其他的實現如Rename,Delete,GetFileSize,FileListDetails,MakeDir等與上面的幾段代碼類似,就不多說了。

注意:實現重命名的功能時,要把新的名字設置給FtpWebRequest對象的RenameTo屬性。連接指定目錄的時候,需要在FtpWebRequest對象所使用的uri中指明。


需要注意的地方
你在編碼時需要注意以下幾點:
    ·除非EnableSsl屬性被設置成true,否作所有數據,包括你的用戶名和密碼都將明文發給服務器,任何監視網絡的人都可以獲取到你連接服務器的驗證信息。如果你連接的ftp服務器提供了SSL,你就應當把EnableSsl屬性設置為true。
    ·如果你沒有訪問ftp服務器的權限,將會拋出SecurityException錯誤
    ·發送請求到ftp服務器需要調用GetResponse方法。當請求的操作完成后,一個FtpWebResponse對象將返回。這個FtpWebResponse對象提供了操作的狀態和已經從ftp服務器上下載的數據。FtpWebResponse對象的StatusCode屬性提供了ftp服務器返回的最后的狀態代碼。FtpWebResponse對象的StatusDescription屬性為這個狀態代碼的描述。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM