c#

C#中FTPS的目录操作方法是什么

小樊
96
2024-08-12 03:56:52
栏目: 编程语言

在C#中,可以使用FtpWebRequest类来进行FTP操作,包括目录操作。以下是一个示例代码,演示如何在FTPS中进行目录操作:

using System;
using System.Net;

class FtpDirectory
{
    public static void ListDirectory(string ftpAddress, string username, string password)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpAddress);
        request.Credentials = new NetworkCredential(username, password);
        request.Method = WebRequestMethods.Ftp.ListDirectory;

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        Console.WriteLine("Directory List:");
        Console.WriteLine();

        using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
        {
            while (!reader.EndOfStream)
            {
                Console.WriteLine(reader.ReadLine());
            }
        }

        response.Close();
    }

    public static void CreateDirectory(string ftpAddress, string username, string password, string newDirectoryName)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpAddress + "/" + newDirectoryName);
        request.Credentials = new NetworkCredential(username, password);
        request.Method = WebRequestMethods.Ftp.MakeDirectory;

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        Console.WriteLine("Directory created successfully.");
        response.Close();
    }

    public static void DeleteDirectory(string ftpAddress, string username, string password, string directoryName)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpAddress + "/" + directoryName);
        request.Credentials = new NetworkCredential(username, password);
        request.Method = WebRequestMethods.Ftp.RemoveDirectory;

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        Console.WriteLine("Directory deleted successfully.");
        response.Close();
    }

    public static void Main()
    {
        string ftpAddress = "ftp://ftp.example.com/";
        string username = "username";
        string password = "password";

        ListDirectory(ftpAddress, username, password);
        CreateDirectory(ftpAddress, username, password, "newDirectory");
        DeleteDirectory(ftpAddress, username, password, "newDirectory");
    }
}

在上面的示例中,ListDirectory方法用于列出FTP服务器上的目录列表,CreateDirectory方法用于创建一个新目录,DeleteDirectory方法用于删除一个目录。您可以根据需要自定义这些方法来执行不同的目录操作。

0
看了该问题的人还看了