c#操作ftp类分享


在C#中,操作FTP通常涉及到使用`System.Net`命名空间下的`FtpWebRequest`类。下面是一个简单的FTP操作类示例,它包括了连接FTP服务器、上传文件和下载文件的基本功能。请注意,这个类是一个简化的版本,主要用于演示目的,你可能需要根据实际需求进行调整和扩展。


using System;
using System.IO;
using System.Net;
using System.Text;

public class FtpClient
{
    private string ftpServer;
    private string ftpUser;
    private string ftpPassword;

    public FtpClient(string server, string user, string password)
    {
        ftpServer = server;
        ftpUser = user;
        ftpPassword = password;
    }

    // 上传文件到FTP服务器
    public void UploadFile(string localFilePath, string remoteFilePath)
    {
        FileInfo fileInfo = new FileInfo(localFilePath);

        string uri = $"ftp://{ftpServer}/{remoteFilePath}";
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential(ftpUser, ftpPassword);

        // 转换为字节数组
        byte[] fileContents = File.ReadAllBytes(localFilePath);
        request.ContentLength = fileContents.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        Console.WriteLine($"Upload File Complete, status {response.StatusDescription}");

        response.Close();
    }

    // 从FTP服务器下载文件
    public void DownloadFile(string remoteFilePath, string localFilePath)
    {
        string uri = $"ftp://{ftpServer}/{remoteFilePath}";
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
        request.Method = WebRequestMethods.Ftp.DownloadFile;

        request.Credentials = new NetworkCredential(ftpUser, ftpPassword);

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        Stream responseStream = response.GetResponseStream();

        FileStream fileStream = new FileStream(localFilePath, FileMode.Create);

        byte[] buffer = new byte[2048];
        int readCount = responseStream.Read(buffer, 0, buffer.Length);
        while (readCount > 0)
        {
            fileStream.Write(buffer, 0, readCount);
            readCount = responseStream.Read(buffer, 0, buffer.Length);
        }

        fileStream.Close();
        responseStream.Close();
        response.Close();

        Console.WriteLine($"Download File Complete.");
    }
}

// 使用示例
class Program
{
    static void Main(string[] args)
    {
        FtpClient ftp = new FtpClient("ftp.example.com", "username", "password");
        ftp.UploadFile(@"C:\local\path\to\file.txt", "/remote/path/to/file.txt");
        ftp.DownloadFile("/remote/path/to/file.txt", @"C:\local\path\downloaded_file.txt");
    }
}

这个类提供了`UploadFile`和`DownloadFile`两个方法,分别用于上传和下载文件。请根据你的FTP服务器地址、用户名和密码进行相应的替换。此外,你可能还需要处理一些异常,比如网络异常、FTP服务器认证失败等,这里为了保持代码的简洁性,没有包含异常处理逻辑。