c# 创建文件夹ftp

///
/// 创建ftp目录
///
/// ftp文件目录.例如“/test/fff/”
///
public bool MakeDir(string dirName)
{
try
{
if (FtpDirExists(dirName)) return true;
string lll = FtpUrl + dirName.TrimStart(’/’);
FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpUrl + dirName.TrimStart(’/’)));
ftpWebRequest.UseBinary = true;
ftpWebRequest.Credentials = new NetworkCredential(UserName, PassWord);
ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse)ftpWebRequest.GetResponse();
response.Close();
response.Dispose();
return true;
}
catch (Exception ex)
{
ErrorLog(ex);
}
return false;
}

需要注意,上述的方法只能创建单级文件夹,创建多级文件夹时会报找不到文件的错误。

///
/// 创建ftp目录
///
/// ftp文件目录.例如“/test/fff/”
///
public bool MakeDir(string dirName)
{
try
{
string fullDir = dirName.Substring(0, dirName.LastIndexOf("/"));
string[] dirs = fullDir.Split(’/’);
string curDir = “/”;
for (int i = 0; i < dirs.Length; i++)
{
string dir = dirs[i];
if (dir != null && dir.Length > 0) //如果是以/开始的路径,第一个为空
{
curDir += dir + “/”;
if (FtpDirExists(curDir)) continue;
string lll = FtpUrl + curDir.TrimStart(’/’);
FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpUrl + curDir.TrimStart(’/’)));
ftpWebRequest.UseBinary = true;
ftpWebRequest.Credentials = new NetworkCredential(UserName, PassWord);
ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse)ftpWebRequest.GetResponse();
response.Close();
response.Dispose();
}
}
return true;
}
catch (Exception ex)
{
ErrorLog(ex);
}
return false;
}

 

你可能感兴趣的