2015-05-29 80 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!