熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

C# FTP操作類

2022-06-13   來源: .NET編程 

  最近要做個用ftp讀取文件並在浏覽器中直接打開圖片的小程序最終寫了這個FTP類庫發上來給大家共享共享

   using System;

   using SystemCollectionsGeneric;

   using SystemText;

   using SystemNet;

   using SystemIO;

  

   namespace Utility

   {

       public class FtpUpDown

       {

  

           string ftpServerIP;

  

           string ftpUserID;

  

           string ftpPassword;

  

           FtpWebRequest reqFTP;

  

           private void Connect(String path)//連接ftp

           {

  

               // 根據uri創建FtpWebRequest對象

  

               reqFTP = (FtpWebRequest)FtpWebRequestCreate(new Uri(path));

  

               // 指定數據傳輸類型

  

               reqFTPUseBinary = true;

  

               // ftp用戶名和密碼

  

               reqFTPCredentials = new NetworkCredential(ftpUserID ftpPassword);

  

           }

  

           public FtpUpDown(string ftpServerIP string ftpUserID string ftpPassword)

           {

               thisftpServerIP = ftpServerIP;

  

               thisftpUserID = ftpUserID;

  

               thisftpPassword = ftpPassword;

           }

  

           //都調用這個

  

           private string[] GetFileList(string path string WRMethods)//上面的代碼示例了如何從ftp服務器上獲得文件列表

           {

               string[] downloadFiles;

               StringBuilder result = new StringBuilder();

               try

               {

                   Connect(path);

  

                   reqFTPMethod = WRMethods;

  

                   WebResponse response = reqFTPGetResponse();

  

                   StreamReader reader = new StreamReader(responseGetResponseStream() SystemTextEncodingDefault);//中文文件名

  

                   string line = readerReadLine();

  

                   while (line != null)

                   {

  

                       resultAppend(line);

  

                       resultAppend(\n);

  

                       line = readerReadLine();

  

                   }

  

                   // to remove the trailing \n

  

                   resultRemove(resultToString()LastIndexOf(\n) );

  

                   readerClose();

  

                   responseClose();

  

                   return resultToString()Split(\n);

  

               }

  

               catch (Exception ex)

               {

                   LogWriteError(Get FileList Error: + exMessage);

                   downloadFiles = null;

  

                   return downloadFiles;

               }

           }

  

           public string[] GetFileList(string path)//上面的代碼示例了如何從ftp服務器上獲得文件列表

           {

               return GetFileList(ftp:// + ftpServerIP + / + path WebRequestMethodsFtpListDirectory);

           }

           public string[] GetFileList()//上面的代碼示例了如何從ftp服務器上獲得文件列表

           {

               return GetFileList(ftp:// + ftpServerIP + / WebRequestMethodsFtpListDirectory);

           }

  

           public void Upload(string filename) //上面的代碼實現了從ftp服務器上載文件的功能

           {

               FileInfo fileInf = new FileInfo(filename);

  

               string uri = ftp:// + ftpServerIP + / + fileInfName;

  

               Connect(uri);//連接

  

               // 默認為true連接不會被關閉

  

               // 在一個命令之後被執行

  

               reqFTPKeepAlive = false;

  

               // 指定執行什麼命令

  

               reqFTPMethod = WebRequestMethodsFtpUploadFile;

  

               // 上傳文件時通知服務器文件的大小

  

               reqFTPContentLength = fileInfLength;

               // 緩沖大小設置為kb

               int buffLength = ;

               byte[] buff = new byte[buffLength];

  

               int contentLen;

  

               // 打開一個文件流(SystemIOFileStream) 去讀上傳的文件

  

               FileStream fs = fileInfOpenRead();

  

               try

               {

  

                   // 把上傳的文件寫入流

  

                   Stream strm = reqFTPGetRequestStream();

  

                   // 每次讀文件流的kb

  

                   contentLen = fsRead(buff buffLength);

  

                   // 流內容沒有結束

  

                   while (contentLen != )

                   {

                       // 把內容從file stream 寫入upload stream

                       strmWrite(buff contentLen);

                       contentLen = fsRead(buff buffLength);

  

                   }

  

                   // 關閉兩個流

  

                   strmClose();

  

                   fsClose();

  

               }

  

               catch (Exception ex)

               {

                    LogWriteError( Upload Error: + exMessage);

               }

  

           }

  

           public bool Download(string filePath string fileName out string errorinfo)////上面的代碼實現了從ftp服務器下載文件的功能

           {

               try

               {

                   String onlyFileName = PathGetFileName(fileName);

  

                   string newFileName = filePath + \\ + onlyFileName;

  

                   if (FileExists(newFileName))

                   {

  

                       errorinfo = stringFormat(本地文件{}已存在無法下載 newFileName);

                       return false;

                   }

                   string url = ftp:// + ftpServerIP + / + fileName;

                   Connect(url);//連接

                   reqFTPCredentials = new NetworkCredential(ftpUserID ftpPassword);

                   FtpWebResponse response = (FtpWebResponse)reqFTPGetResponse();

                   Stream ftpStream = responseGetResponseStream();

                   long cl = responseContentLength;

                   int bufferSize = ;

                   int readCount;

                   byte[] buffer = new byte[bufferSize];

                   readCount = ftpStreamRead(buffer bufferSize);

  

                   FileStream outputStream = new FileStream(newFileName FileModeCreate);

                   while (readCount > )

                   {

                       outputStreamWrite(buffer readCount);

                       readCount = ftpStreamRead(buffer bufferSize);

                   }

                   ftpStreamClose();

                   outputStreamClose();

                   responseClose();

  

                   errorinfo = ;

  

                   return true;

  

               }

  

               catch (Exception ex)

               {

                   errorinfo = stringFormat(因{}無法下載 exMessage);

  

                   return false;

  

               }

  

           }

  

           //刪除文件

  

           public void DeleteFileName(string fileName)

           {

               try

               {

                   FileInfo fileInf = new FileInfo(fileName);

  

                   string uri = ftp:// + ftpServerIP + / + fileInfName;

  

                   Connect(uri);//連接

  

                   // 默認為true連接不會被關閉

  

                   // 在一個命令之後被執行

  

                   reqFTPKeepAlive = false;

  

                   // 指定執行什麼命令

  

                   reqFTPMethod = WebRequestMethodsFtpDeleteFile;

  

                   FtpWebResponse response = (FtpWebResponse)reqFTPGetResponse();

                   responseClose();

  

               }

  

               catch (Exception ex)

               {

                   LogWriteError(刪除錯誤: + exMessage);

               }

  

           }

  

           //創建目錄

  

           public void MakeDir(string dirName)

           {

               try

               {

                   string uri = ftp:// + ftpServerIP + / + dirName;

  

                   Connect(uri);//連接

  

                   reqFTPMethod = WebRequestMethodsFtpMakeDirectory;

  

                   FtpWebResponse response = (FtpWebResponse)reqFTPGetResponse();

  

                   responseClose();

  

               }

  

               catch (Exception ex)

               {

                   LogWriteError(創建目錄錯誤: + exMessage);

               }

  

           }

  

           //刪除目錄

  

           public void delDir(string dirName)

           {

               try

               {

                   string uri = ftp:// + ftpServerIP + / + dirName;

  

                   Connect(uri);//連接

  

                   reqFTPMethod = WebRequestMethodsFtpRemoveDirectory;

  

                   FtpWebResponse response = (FtpWebResponse)reqFTPGetResponse();

  

                   responseClose();

  

               }

  

               catch (Exception ex)

               {

                   LogWriteError(刪除目錄錯誤: + exMessage);

               }

  

           }

  

           //獲得文件大小

  

           public long GetFileSize(string filename)

           {

  

  

  

               long fileSize = ;

  

               try

               {

  

                   FileInfo fileInf = new FileInfo(filename);

  

                   string uri = ftp:// + ftpServerIP + / + fileInfName;

  

                   Connect(uri);//連接

  

                   reqFTPMethod = WebRequestMethodsFtpGetFileSize;

  

                   FtpWebResponse response = (FtpWebResponse)reqFTPGetResponse();

  

                   fileSize = responseContentLength;

  

                   responseClose();

  

               }

  

               catch (Exception ex)

               {

                   LogWriteError(獲得文件大小錯誤: + exMessage);

               }

  

               return fileSize;

  

           }

  

           //文件改名

  

           public void Rename(string currentFilename string newFilename)

           {

               try

               {

                   FileInfo fileInf = new FileInfo(currentFilename);

                   string uri = ftp:// + ftpServerIP + / + fileInfName;

                   Connect(uri);//連接

                   reqFTPMethod = WebRequestMethodsFtpRename;

                   reqFTPRenameTo = newFilename;

                   FtpWebResponse response = (FtpWebResponse)reqFTPGetResponse();

                   responseClose();

  

               }

  

               catch (Exception ex)

               {

                   LogWriteError(文件改名錯誤: + exMessage);

               }

  

           }

           //讀取文件

  

           public Stream ReadFile(string fileName)

           {

               try

               {

                   string url = ftp:// + ftpServerIP + / + fileName;

                   Connect(url);//連接

                   reqFTPCredentials = new NetworkCredential(ftpUserID ftpPassword);

                   FtpWebResponse response = (FtpWebResponse)reqFTPGetResponse();

                   Stream ftpStream = responseGetResponseStream();

                   return ftpStream;

               }

  

               catch (Exception ex)

               {

                   LogWriteError(讀取文件錯誤: + exMessage);

                   return null;

               }

  

           }

  

           //獲得文件明晰

  

           public string[] GetFilesDetailList()

           {

  

               return GetFileList(ftp:// + ftpServerIP + / WebRequestMethodsFtpListDirectoryDetails);

  

           }

  

           //獲得文件明晰

  

           public string[] GetFilesDetailList(string path)

           {

  

               return GetFileList(ftp:// + ftpServerIP + / + path WebRequestMethodsFtpListDirectoryDetails);

  

           }

  

           // 文件存在檢查

           public bool fileCheckExist(string fileName)

           {

               bool success = false;

               FtpWebResponse response = null;

               StreamReader reader = null;

               try

               {

                   string url = ftp:// + ftpServerIP + / + fileName;

                   Connect(url);//連接

                   reqFTPCredentials = new NetworkCredential(ftpUserID ftpPassword);

                   response = (FtpWebResponse)reqFTPGetResponse();

                   reader = new StreamReader(responseGetResponseStream());

                   string line = readerReadLine();

                   if (line != null)

                   {

                       success = true;

                   }

               }

               catch (Exception)

               {

                   success = false;

               }

               finally

               {

                   if (reader != null)

                   {

                       readerClose();

                   }

  

                   if (response != null)

                   {

                       responseClose();

                   }

               }

               return success;

           }

       }

   }


From:http://tw.wingwit.com/Article/program/net/201311/11445.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.