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

C#中如何基于文件名列表为每个对应文本文件创建自定义类对象

实现方案

注意:C# 系统类库 System.IO 命名空间下已存在 File 静态类,为了避免调用冲突,建议先将你自定义的类重命名,比如改成 CustomFile:

// 重命名后的自定义类
public class CustomFile
{
    public string Attribute1 { get; set; }
    public string Attribute2 { get; set; }
    public string Attribute3 { get; set; }
    public string Attribute4 { get; set; }
}

核心逻辑是遍历文件名列表、读取对应文件内容、解析属性赋值、存入结果集合,下面给出两种最常见文件存储格式的实现代码,如果你用的是CSV、JSON等其他格式,调整解析部分的逻辑即可。


场景1:文件按行存储4个属性,第一行对应Attribute1、第二行对应Attribute2,以此类推

using System.IO;
using System.Collections.Generic;

// 替换为你实际的文件存放根目录
const string FileRootPath = @"C:\Your\File\Storage\Path";
List<CustomFile> resultList = new List<CustomFile>();

foreach (string fileName in filenames)
{
    string fullPath = Path.Combine(FileRootPath, fileName);
    // 跳过不存在的文件避免报错
    if (!File.Exists(fullPath))
    {
        continue;
    }
    try
    {
        string[] lines = File.ReadAllLines(fullPath);
        // 不足4行的属性默认赋值为空字符串,避免索引越界
        CustomFile fileObj = new CustomFile
        {
            Attribute1 = lines.Length >= 1 ? lines[0].Trim() : string.Empty,
            Attribute2 = lines.Length >= 2 ? lines[1].Trim() : string.Empty,
            Attribute3 = lines.Length >= 3 ? lines[2].Trim() : string.Empty,
            Attribute4 = lines.Length >= 4 ? lines[3].Trim() : string.Empty
        };
        resultList.Add(fileObj);
    }
    catch (IOException ex)
    {
        // 按需添加日志记录读取失败的原因
        Console.WriteLine($"读取文件{fileName}失败:{ex.Message}");
    }
}

场景2:文件为键值对格式,每行格式为Attribute1=xxx

foreach (string fileName in filenames)
{
    string fullPath = Path.Combine(FileRootPath, fileName);
    if (!File.Exists(fullPath))
    {
        continue;
    }
    try
    {
        Dictionary<string, string> keyValues = new Dictionary<string, string>();
        foreach (string line in File.ReadAllLines(fullPath))
        {
            if (string.IsNullOrWhiteSpace(line)) continue;
            // 按第一个等号分割,避免属性值里包含等号导致解析错误
            string[] parts = line.Split('=', 2);
            if (parts.Length == 2)
            {
                keyValues[parts[0].Trim()] = parts[1].Trim();
            }
        }
        CustomFile fileObj = new CustomFile
        {
            Attribute1 = keyValues.TryGetValue(nameof(CustomFile.Attribute1), out string v1) ? v1 : string.Empty,
            Attribute2 = keyValues.TryGetValue(nameof(CustomFile.Attribute2), out string v2) ? v2 : string.Empty,
            Attribute3 = keyValues.TryGetValue(nameof(CustomFile.Attribute3), out string v3) ? v3 : string.Empty,
            Attribute4 = keyValues.TryGetValue(nameof(CustomFile.Attribute4), out string v4) ? v4 : string.Empty
        };
        resultList.Add(fileObj);
    }
    catch (IOException ex)
    {
        Console.WriteLine($"读取文件{fileName}失败:{ex.Message}");
    }
}

3000+文件性能优化方案

如果串行读取速度慢,可以改用并行循环提升效率,注意使用线程安全的集合存储结果:

using System.Collections.Concurrent;

ConcurrentBag<CustomFile> parallelResult = new ConcurrentBag<CustomFile>();
Parallel.ForEach(filenames, fileName =>
{
    string fullPath = Path.Combine(FileRootPath, fileName);
    if (!File.Exists(fullPath)) return;
    try
    {
        // 解析逻辑和上面串行逻辑完全一致,按需替换即可
        string[] lines = File.ReadAllLines(fullPath);
        CustomFile fileObj = new CustomFile
        {
            Attribute1 = lines.Length >= 1 ? lines[0].Trim() : string.Empty,
            Attribute2 = lines.Length >= 2 ? lines[1].Trim() : string.Empty,
            Attribute3 = lines.Length >= 3 ? lines[2].Trim() : string.Empty,
            Attribute4 = lines.Length >= 4 ? lines[3].Trim() : string.Empty
        };
        parallelResult.Add(fileObj);
    }
    catch (IOException ex)
    {
        Console.WriteLine($"读取文件{fileName}失败:{ex.Message}");
    }
});
// 如需转为普通List直接调用ToList方法即可
List<CustomFile> resultList = parallelResult.ToList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:54:03