C#读取文本文件

该代码段展示了一个方法,用于从指定的文件夹中读取.txt文本文件,使用StreamReader逐行读取内容。它首先检查并创建必要的目录结构,然后解析每行数据(格式为ID|SampleTime|Value),将数据转换为Model.DataValue对象并添加到列表中。如果遇到异常,日志会记录错误信息。
摘要由CSDN通过智能技术生成

根据文件名到对应文件夹中读取对应文本文件(.txt),并返回数据集合。

使用流读取类StreamReader,一行一行读取 ReadLine()

文本格式

 

public static List<Model.DataValue> ReadData(string FileName)
        {
            List<Model.DataValue> list = new List<Model.DataValue>();
            try
            {
                string DataLogPath = "RootFolder";
                string FilePath = FileName.Substring(0, 8);  //截取子文件夹名称
                //判断第一个父文件夹是否存在
                if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\" + DataLogPath))
                {
                    //不存在就创建文件夹
                    Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\" + DataLogPath);
                }
                //判断子文件夹是否存在
                if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\" + DataLogPath + "\\" + FilePath))
                {
                    Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\" + DataLogPath + "\\" + FilePath);
                }
                //打开文件
                StreamReader sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "\\" + DataLogPath + "\\" + FilePath + "\\" + FileName + ".log", Encoding.Default);
                String line;
                //按行读取文件
                while ((line = sr.ReadLine()) != null)
                {
                    //格式为:ID|SampleTime|Value
                    if (!string.IsNullOrEmpty(line) && line.Contains("|"))
                    {
                        string[] strs = line.Split('|');
                        long ID = long.Parse(strs[0]);
                        DateTime sampletime = Convert.ToDateTime(strs[1]);
                        double Value = Convert.ToDouble(strs[2]);

                        Model.DataValue data = new Model.DataValue();
                        data.ID = ID;
                        data.SampleTime = sampletime;
                        data.Value = Value;
                        list.Add(data);
                    }
                }
                sr.Close();
            }
            catch (Exception ex)
            {
                LogFile.WriteLogExe("读取文件数据异常:" + ex.Message);
            }

            return list;
        }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值