2015-05-29 60 views
1

我有一个文本文件附加了所有信息,并且我想将该信息读取到列表中。这是我的文本文件的设计。阅读文本文件中的附加信息

------->26/05/2015 17:15:52<------------------ 
Index :0-0 
Index :1-0 
Index :2-20150527 
Index :3-182431 
------->27/05/2015 17:15:52<------------------ 
Index :0-0 
Index :1-0 
Index :2-20150527 
Index :3-182431 
------->28/05/2015 17:15:52<------------------ 
Index :0-0 
Index :1-0 
Index :2-20150527 
Index :3-182431 

我的问题是我怎么能阅读这些信息到我的清单,我知道我可以通过使用行线,但我怎么知道我正在读一个新的项目?

+1

该行以'------->开始的事实应该告诉你它是*一个新项目。* –

+0

我猜'' - >'显示你一个新项目是在给定的时间添加?或者,只有一个占位符附加了一些东西,但不包含文件的内容? – ZoolWay

+0

我认为你应该存储到目前为止阅读的行数。当你继续监视文件时,只需阅读新文件。 –

回答

2

首先,如果这意味着我们应该定义“新”字:

  • 没有在以前的迭代至今读取文件

  • 新节假设你的意思是新的节那么你可以定义这样的类代表物品:

    class Item 
    { 
        public List<string> Indexes; 
        public string Header; 
    
        public Item() 
        { 
         Indexes= new List<string>(); 
        } 
    } 
    

    而且使用简单的循环,这样的解析文件:

    List<Item> items = new List<Item>(); 
    
        var lines = File.ReadAllLines("path-to-file"); 
        Item currentItem = null; 
        foreach (var line in lines) 
        { 
         if (line.StartsWith("------->")) 
         { 
          if (currentItem != null) 
          { 
           items.Add(currentItem); 
          } 
          currentItem=new Item(); 
          currentItem.Header = line; 
         } 
         else if (currentItem != null) 
         { 
          currentItem.Indexes.Add(line); 
         } 
        } 
        if (currentItem!=null) 
         items.Add(currentItem); 
    

    如果你的意思是新的未读到目前为止,那么你应该在“项”级也进入日期可能存储和比较读取入境日期那些已经存在于集合中的只读了新的集合。

    此外,你应该考虑如果文件不时被清除(旋转),那么你必须决定读取整个文件是否有意义,或者你应该只从目前没有读取的行中读取一些变量来存储先前迭代中读取的行数。和其他这样的事情。

  • +0

    非常感谢,这是我需要:) –

    +0

    不客气;) –

    -1

    你会想使用这样的代码来解析文件。

    //load the whole file in to memory 
    var lines = File.ReadAllLines("path-to-file"); //don't forget to add using System.IO; 
    
    //you will have to fill in your specific logic 
    MyCustomObject currentObject = null; 
    List<MyCustomObject> objects = new List<MyCustomObject>(); 
    
    //loop over the lines in the file 
    foreach(var line in lines) { 
        if(line.StartsWith("------->")) { 
         //header line 
    
         //Again, fill in your logic here 
         currentObject = new MyCustomObject(); 
         currentObject.SetHeader(line); 
         objects.Add(currentObject); 
        } else { 
         //body line 
    
         //double check that the file isn't malformed 
         if(currentObject == null) throw new Exception("Missing header record at beginning of file!"); 
    
         //process the line 
         currentObject.AddLine(line); 
        } 
    } 
    //done!