C# ftp 上传文件如果服务器文件夹不存在就创建文件如果需要创建多级目录该怎么创建
要在FTP服务器上创建多级目录,您可以使用以下代码示例:
using System;
using System.Net;
class Program
{
static void Main()
{
string serverAddress = "ftp://ftp.example.com";
string username = "username";
string password = "password";
string remoteFolderPath = "/path/to/remote/folder/subfolder";
// 创建FTP请求对象
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverAddress + remoteFolderPath);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential(username, password);
try
{
// 发送创建目录的请求
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine($"目录 {remoteFolderPath} 创建成功");
}
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
// 目录已存在
Console.WriteLine($"目录 {remoteFolderPath} 已存在");
}
else
{
// 其他错误
Console.WriteLine($"创建目录时发生错误: {ex.Message}");
}
}
}
}
请将serverAddress、username、password和remoteFolderPath替换为实际的FTP服务器地址、用户名、密码和要创建的目录路径
原文地址: https://www.cveoy.top/t/topic/hTq2 著作权归作者所有。请勿转载和采集!