前面几篇博客讲的都是对文件的操作,今天跟大家说一说对目录的操作,先让我们从创建目录开始说起吧。
创建目录很简单,首先创建一个ftp对象,然后将参数传进去,接着告诉ftp对象需要执行什么操作即可。
下面是一个创建目录的小例子:
/// <summary>
/// FTP创建目录
/// </summary>
/// <param name="dirName">目录名</param>
/// <param name="ftpServerIP">服务器地址</param>
/// <param name="ftpUserID">ftp用户名</param>
/// <param name="ftpPassword">ftp密码</param>
/// <returns></returns>
public string CreateDir(string dirName, string ftpServerIP, string ftpUserID, string ftpPassword)
{
string sRet = "OK";
try
{
string uri = ftpServerIP + "/" + dirName;
FtpWebRequest reqFTP; // 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); // ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); // 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false; // 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; // 指定数据传输类型
reqFTP.UseBinary = true; FtpWebResponse respFTP = (FtpWebResponse)reqFTP.GetResponse();
respFTP.Close();
}
catch (Exception ex)
{
sRet = ex.Message;
}
return sRet;
}
代码很简单,很简洁。ftp相关的操作封装的都挺好,所以我们用起来才会觉得很简单,很好用。我们在开发的时候就要向着这样的目标迈进。各个模块具有独立性,只要哪里需要,拿过来就能用。时刻谨记面向对象的思想。