正在读取C#中用虚线分隔的文本文件



应用程序日志文件中的文本由----虚线分隔。我把那篇文章当作一个字符串来读。

字符串如下:

8/23 17:40:54:761  6948 - AUDIT - Logging: Set ABC
-----------------------------------------
08/23 17:40:54:772  6948 - TRANSACTION - Logging: FullFileName:/XYZ/
Message:Some Message 
Type : Information                          
---------------------------------------------
08/23 17:40:54:844  6948 - INFO - Logging: End of Control_Loaded  

如何将这个字符串转换为一个数组或字符串列表,以便每个字符串的虚线之间都有一段。例如:AUDIT段落为字符串[0],TRANSACTION段落为字符串[1],依此类推。。。。直到最后一段没有虚线的地方。

这是我尝试过的:

string textFromFile = _streamReader.ReadToEnd();

string[] paragraphs = textFromFile.Split(
new char[] { '-','-','-','-','-','-'}, StringSplitOptions.RemoveEmptyEntries);

好了:

IEnumerable<string> ReadParagraphs(IEnumerable<string> source)
{
var output = new List<string>();
foreach (var line in source)
{
if (line == "---------------------------------------------")
{
if (output.Count > 0)
{
yield return String.Join(Environment.NewLine, output);
output.Clear();
}
}
else
{
output.Add(line);
}
}
if (output.Count > 0)
{
yield return String.Join(Environment.NewLine, output);
}
}

最新更新