You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 基于FluentFTP读取FTP文件内容为字符串的实现方法咨询

解答

内置方法说明

FluentFTP没有直接封装逐行读取返回字符串的内置方法,但是提供了OpenRead()接口获取远程文件的可读流,基于流即可实现逐行读取,不需要把整个文件下载到本地存储后再处理。

提示:你当前的CustomFtpClient存在冗余设计:已经继承了FtpClient,无需额外声明私有FtpClient Client属性重复实例化,直接调用基类继承的方法即可,避免多余的FTP连接占用。

实现代码

修正后的CustomFtpClient类(新增逐行读取方法)

using FluentFTP;
using System.IO;
using System.Collections.Generic;
using System.Text;

public class CustomFtpClient : FtpClient
{
    public CustomFtpClient(string host, int port, string username, string password) :
        base(host, port, username, password)
    {
        // 直接用基类的AutoConnect,不需要重复实例化FtpClient
        this.AutoConnect();
        this.BufferSize = 4 * 1024;
    }

    // 原有ReadFile方法保留,直接调用基类方法
    public string ReadFile(string remoteFileName)
    {
        return this.ReadAllText(remoteFileName);
    }

    /// <summary>
    /// 逐行读取远程文件,返回所有行的集合
    /// </summary>
    public List<string> ReadLines(string remoteFileName, Encoding encoding = null)
    {
        encoding ??= Encoding.UTF8;
        var lines = new List<string>();
        // 打开远程文件流
        using (var stream = this.OpenRead(remoteFileName))
        using (var reader = new StreamReader(stream, encoding))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                lines.Add(line);
            }
        }
        return lines;
    }

    /// <summary>
    /// 逐行读取后拼接为完整字符串,保留换行符,兼容原有ReadFile的调用习惯
    /// </summary>
    public string Read(string remoteFileName, Encoding encoding = null)
    {
        encoding ??= Encoding.UTF8;
        var sb = new StringBuilder();
        using (var stream = this.OpenRead(remoteFileName))
        using (var reader = new StreamReader(stream, encoding))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                sb.AppendLine(line);
            }
        }
        return sb.ToString();
    }
}

调用示例

var customFtpClient = new CustomFtpClient(ftpurl, 21, ftpusername, ftppwd);
var listedfiles = customFtpClient.GetListing("inbound");
var onlyedifiles = listedfiles.Where(z =>
    z.FullName.ToLower().Contains(".txt") || z.FullName.ToLower().Contains("940"))
    .ToList();

foreach (var item in onlyedifiles)
{
    // 方式1:获取所有行的集合单独处理
    List<string> fileLines = customFtpClient.ReadLines(item.FullName);
    foreach (var line in fileLines)
    {
        // 逐行处理逻辑
    }

    // 方式2:直接获取拼接好的完整字符串
    string fileStr = customFtpClient.Read(item.FullName);
}

内容的提问来源于stack exchange,提问作者Berkay Kulak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:06:08