如何借助filelist.dat循环读取外部struct文件并输出内容
C# 读取外部Struct文件并格式化输出方案
第一步:修正可序列化的Struct定义
首先你的struct定义需要调整为C#标准写法,并且加上[Serializable]特性(因为要从二进制文件读取结构体数据):
using System; [Serializable] public struct DataStruct { public string Name; public int A; public int B; public int C; public int D; }
注意:如果你的struct文件是用二进制序列化写入的,必须加这个特性;如果是自定义文本格式,那读取逻辑要调整,但通常结构体存储用二进制更高效。
第二步:核心实现代码
以下是完整的实现逻辑,包含读取文件名列表、逐个读取结构体、格式化输出到控制台和文件:
using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; class Program { static void Main(string[] args) { // U盘路径,根据实际情况替换,比如 @"E:\" string usbPath = @"E:\"; string fileListPath = Path.Combine(usbPath, "filelist.dat"); string outputFilePath = Path.Combine(usbPath, "text.txt"); // 1. 读取filelist.dat中的所有文件名(假设每行一个文件名) if (!File.Exists(fileListPath)) { Console.WriteLine("filelist.dat不存在"); return; } string[] structFileNames = File.ReadAllLines(fileListPath); // 准备输出流,写入text.txt using (StreamWriter writer = new StreamWriter(outputFilePath, false)) { // 写入表头 string header = $"{"name",-10} {"A",-5} {"B",-5} {"C",-5} {"D",-5}"; Console.WriteLine(header); writer.WriteLine(header); // 2. 循环读取每个struct文件 BinaryFormatter formatter = new BinaryFormatter(); foreach (string fileName in structFileNames) { string structFilePath = Path.Combine(usbPath, fileName); if (!File.Exists(structFilePath)) { Console.WriteLine($"警告:文件 {fileName} 不存在"); continue; } // 读取结构体数据 try { using (FileStream fs = new FileStream(structFilePath, FileMode.Open)) { DataStruct data = (DataStruct)formatter.Deserialize(fs); // 格式化输出,用对齐保证格式统一 string outputLine = $"{data.Name,-10} {data.A,-5} {data.B,-5} {data.C,-5} {data.D,-5}"; Console.WriteLine(outputLine); writer.WriteLine(outputLine); } } catch (Exception ex) { Console.WriteLine($"读取文件 {fileName} 出错:{ex.Message}"); } } } Console.WriteLine("处理完成,结果已保存到text.txt"); } }
关键注意事项
- 序列化一致性:如果你的struct文件不是用
BinaryFormatter序列化写入的,这段代码会报错。如果是自定义的存储格式(比如文本每行存一个字段),需要修改读取逻辑,比如用StreamReader逐行读取并赋值给struct字段。 - 路径问题:务必替换代码中的
usbPath为你的U盘实际路径,比如@"F:\"。 - 编码问题:如果
filelist.dat是用非UTF-8编码保存的,需要在File.ReadAllLines中指定编码,比如File.ReadAllLines(fileListPath, Encoding.Default)。 - 权限问题:确保程序有U盘的读写权限,避免因权限不足导致无法访问文件。
内容的提问来源于stack exchange,提问作者Robert Hohlt
相关产品推荐
相关产品推荐

