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文件的操作一般都会同时出现,配合完成一系列的工作,之后的博客中还会继续更新,敬请关注!

上一篇:Python操作redis系列之 列表(list) (四)


下一篇:一个demo让你彻底理解Android触摸事件的并发