根据文件名到对应文件夹中读取对应文本文件(.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;
}