2010-09-08 52 views
1

我有一个日志文件可以变得非常大。如何读取特定格式的数据

我的日志文件中的信息是以某种格式存在的,我想将它们分隔成一个独立的数据块。

例如,

这是开始。

等等等等

等等等等等等等等等等等等

胡说

这是开始。

等等等等

等等等等等等等等等等等等

等等等等等等等等等等等等

等等等等等等等等等等等等

胡说

我想要得到的信息从“这是起点”到下一个“这是起点”开始之前。做这个的最好方式是什么?我的代码是在C#中。

+0

线是由一个新的行分开? – halfdan 2010-09-08 00:47:18

+0

可能会或可能不会。除“这是开始”外,没有这种格式。 – user393148 2010-09-08 00:55:58

回答

1

下面的代码将所述文件分割成由"This is the start."线划定的块,并调用的回调方法来处理每个数据块:

public static void ProcessInChunks(string inputFilename, 
    string delimiter, Action<IEnumerable<string>> processChunk) 
{ 
    using (var enumerator = File.ReadLines(inputFilename).GetEnumerator()) 
    { 
     if (!enumerator.MoveNext()) 
      // The file is empty. 
      return; 

     var firstLine = enumerator.Current; 
     if (firstLine != delimiter) 
      throw new InvalidOperationException(
       "Expected the first line to be a delimiter."); 

     List<string> currentChunk = new List<string>(); 

     while (enumerator.MoveNext()) 
     { 
      if (enumerator.Current == delimiter) 
      { 
       processChunk(currentChunk); 
       currentChunk = new List<string>(); 
      } 
      else 
       currentChunk.Add(enumerator.Current); 
     } 
     processChunk(currentChunk); 
    } 

用法:

ProcessInChunks(@"myfile.log", "This is the start.", 
    chunk => { /* do something here */ }); 
+0

感谢Timwi的回答。我会试试这个。我的另一个问题是,这是阅读大文件的最佳方式吗? – user393148 2010-09-08 00:56:37

+0

@ user393148 - 对于编程中的一大类问题,没有简单而直接的答案。你总是需要看看每个人的情况。我刚刚编辑了这个答案,以使它对于非常大的文件更加高效。我以前的版本会将整个文件加载到内存中,但新版本会逐步处理它。 – Timwi 2010-09-08 01:14:36

+0

谢谢Timwi ... – user393148 2010-09-08 17:56:33

0

如果可以”不会改变日志创建过程,@Timwi的答案会很好。如果您可以调整日志创建过程,则可以在每次要写入This is the start.时创建新的日期标记日志文件名。这将创建多个日志文件,但它们已经以所需的方式分割。显然如果找到的文本可以改变,这将无法工作。

+0

谢谢爱德华。我正在努力将其变为标准格式。在此之前,我必须使用解决方法。谢谢 – user393148 2010-09-08 17:48:38