2011-08-30 56 views
2

我在哪裏工作,我們有一個包含這樣行日誌文件:在一個無序的日誌文件中搜索

這是要這樣寫的:

31 |年(4)|月(4)|日(2)|小時(2)|分鐘(2)| 000000 |設施(3)|徽章(5)| 0001

因此,有應該是每個記錄的線,但發生這樣的東西:

 
31201007192000000000161206930004 
31201007192001000000161353900004 
31201031201007192004000000161204690004 
31201007192004000000090140470004 
31201007192005000000090148140004 
3120100719200500031201007191515000000161597180001 
31201007191700000000161203490001 
31201007191700000000161203490001 
31201007191700000000161202830001 
31201007191700000000 

這是因爲這是應該讀取文件的軟件,有時會錯過一些newests記錄和負責人將舊記錄複製到文件末尾。所以基本上就是這樣,因爲人類的錯誤。

當記錄未保存在數據庫中時,我必須搜索該文件。起初,我只是做了一個通過文件中的每條記錄的cicle,但它非常慢,上面提到的問題使它變慢。這種方法我現在所擁有的是一個正則表達式是這樣的:

//Starts Reader 
StreamReader reader = new StreamReader(path); 
string fileLine = reader.ReadLine(); 
while (!reader.EndOfStream) 
{ 
    //Regex Matcher 
    Regex rx = new Regex(@"31\d\d\d\d\d\d\d\d\d\d\d\d000000161\d\d\d\d\d0001"); 

    //Looks for all valid lines 
    MatchCollection matches = rx.Matches(fileLine); 

    //Compares each match against what we are looking for 
    foreach (Match m in matches) 
    { 
    string s = m.Value; 
    compareLine(date, badge, s); 
    } 

    reader.ReadLine(); 
} 
reader.Close(); //Closes reader 

我的問題是:什麼是通過文件搜索的好方法?我應該先訂購/清潔它嗎?

+0

單串和搜索做一個命令行['sort'(http://en.wikipedia.org/wiki/Sort_(UNIX)),這將是比任何你可以在C#做的更快 –

回答

2

你可能是最好關閉以下步驟:

  • 分析每一行成一個對象。一個結構應該適合這些行。包括一個DateTime對象以及任何其他相關字段。如果你把它清理一下,這可以用Regex很容易地完成。使用捕獲組和中繼器。一年中,您可以使用(\d{4})獲得4個數字,而不是\d\d\d\d
  • 創建一個將每行保存爲對象的List<MyStruct>
  • 使用LINQ通過列表來搜索,例如:

    var searchResults = from eachEntry in MyList 
            where eachEntry.Date > DateTime.Now 
            and eachEntry.facility.Contains("003") 
            select eachEntry;

此外,該行添加到您的正則表達式,它會加速這一過程,如果僅靠幾毫秒:

MatchCollection matches = rx.Matches(fileLine, RegexOptions.Compiled); 
0

如果您知道(事先)您正在尋找哪個條目,ie iee你完全知道你正在尋找的日期,設施和批次,你根本不需要解析數據。這可能是更快地產生期望的字符串,並做一個簡單的字符串搜索,而不是使用正則表達式:

string expectedValue = getExpectedValue(date, badge); 
// expectedValue = "31201007192000000000161206930004" 
foreach (string line in lines) 
{ 
    if (line.IndexOf(expectedValue) >= 0) 
    { 
      // record found 
    } 
} 

如果你只關心羯羊該文件包含您的ID或沒有,你可以閱讀完整的文件轉換成通過

string completeFile = GetFileContents(file); 
if (completeFile.IndexOf(expectedValue) >= 0) 
{ 
    // record found 
}