c# ftp判断远程服务器有没有ABC文件夹如果没有就创建
您可以使用System.Net.FtpWebRequest类来连接到FTP服务器并执行相关操作。以下是一个示例代码,用于检查远程服务器是否存在/ABC文件夹并在不存在时创建它:
using System;
using System.Net;
class Program
{
static void Main(string[] args)
{
string ftpServer = "ftp://your_ftp_server";
string folderPath = "/ABC";
if (IsFolderExists(ftpServer, folderPath))
{
Console.WriteLine("The folder already exists.");
}
else
{
if (CreateFolder(ftpServer, folderPath))
{
Console.WriteLine("The folder has been created successfully.");
}
else
{
Console.WriteLine("Failed to create the folder.");
}
}
}
static bool IsFolderExists(string ftpServer, string folderPath)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + folderPath);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.EnableSsl = false;
request.Credentials = new NetworkCredential("username", "password");
try
{
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
else
{
throw;
}
}
}
static bool CreateFolder(string ftpServer, string folderPath)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + folderPath);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.EnableSsl = false;
request.Credentials = new NetworkCredential("username", "password");
try
{
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch (WebException ex)
{
throw;
}
}
}
在上面的代码中,您需要将"your_ftp_server"替换为您的FTP服务器地址,并将"username"和"password"替换为您的FTP凭据。然后,代码将通过调用IsFolderExists方法来检查指定的文件夹是否存在,如果不存在,则调用CreateFolder方法来创建文件夹。
请确保在使用此代码之前,您已经添加了对System.Net命名空间的引用,并根据您的实际情况进行相应的修改
原文地址: https://www.cveoy.top/t/topic/hPYB 著作权归作者所有。请勿转载和采集!