FTP文件操作之刪除文件
上面我已經介紹了利用ftp進行上傳跟下載,接下來跟大家分享的是刪除ftp服務器上的文件的部分。有了上傳,有了下載,那么刪除自然也是不能少的。
刪除相對於上傳跟下載更簡單一些,它不需要進行文件的傳輸,只需向FTP服務器發送一個刪除的命令。
下面是一個刪除功能的完整示例:
/// <summary> /// FTP刪除文件 /// </summary> /// <param name="ftpPath">ftp文件路徑</param> /// <param name="userId">ftp用戶名</param> /// <param name="pwd">ftp密碼</param> /// <param name="fileName">ftp文件名</param> /// <returns></returns> public string DeleteFile(string ftpPath,string userId,string pwd, string fileName) { string sRet = "刪除成功!"; FtpWebResponse Respose = null; FtpWebRequest reqFTP = null; Stream localfile = null; Stream stream = null; try { //根據uri創建FtpWebRequest對象 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(string.Format(@"{0}{1}", ftpPath, fileName))); //提供賬號密碼的驗證 reqFTP.Credentials = new NetworkCredential(userId, pwd); //默認為true是上傳完后不會關閉FTP連接 reqFTP.KeepAlive = false; //執行刪除操作 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; Respose = (FtpWebResponse)reqFTP.GetResponse(); } catch (Exception ex) { sRet = ex.Message; } finally { //關閉連接跟流 if (Respose != null) Respose.Close(); if (localfile != null) localfile.Close(); if (stream != null) stream.Close(); } //返回執行狀態 return sRet; }
不難發現,刪除所用的代碼比上傳跟下載少了很多,這也說明了它比之前的兩個功能更簡單一些。雖然簡單但同樣重要,ftp文件的操作一般都會同時出現,配合完成一系列的工作,之后的博客中還會繼續更新,敬請關注!
