在ftp服务器上创建文件夹时,如何使用C#在ftp服务器上创建目录?

Yannick Rich..

34

如果要创建嵌套目录,可以使用以下答案

没有干净的方法来检查ftp上是否存在文件夹,因此您必须循环并创建当时的所有嵌套结构文件夹

public static void MakeFTPDir(string ftpAddress, string pathToCreate, string login, string password, byte[] fileContents, string ftpProxy = null)

{

FtpWebRequest reqFTP = null;

Stream ftpStream = null;

string[] subDirs = pathToCreate.Split('/');

string currentDir = string.Format("ftp://{0}", ftpAddress);

foreach (string subDir in subDirs)

{

try

{

currentDir = currentDir + "/" + subDir;

reqFTP = (FtpWebRequest)FtpWebRequest.Create(currentDir);

reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;

reqFTP.UseBinary = true;

reqFTP.Credentials = new NetworkCredential(login, password);

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

ftpStream = response.GetResponseStream();

ftpStream.Close();

response.Close();

}

catch (Exception ex)

{

//directory already exist I know that is weak but there is no way to check if a folder exist on ftp...

}

}

}

仅供参考,假设您使用的是较新的C#版本,则可以执行以下操作:在(ex.Response为FtpWebResponse ftpResponse && ftpResponse.StatusDescription.Contains(“文件存在”))时捕获(WebException ex) (2认同)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值