你可以很容易地做到這一點。
這個問題有三個部分。
1)如何找到文件中的一行開始。做到這一點的唯一方法是從文件中讀取行,保留一個列表,記錄該行文件中的起始位置。例如
List lineMap = new List();
lineMap.Add(0); // Line 0 starts at location 0 in the data file (just a dummy entry)
lineMap.Add(0); // Line 1 starts at location 0 in the data file
using (StreamReader sr = new StreamReader("DataFile.txt"))
{
String line;
int lineNumber = 1;
while ((line = sr.ReadLine()) != null)
lineMap.Add(sr.BaseStream.Position);
}
2)讀取並解析索引文件到字典中。
Dictionary index = new Dictionary();
using (StreamReader sr = new StreamReader("IndexFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
string[] parts = line.Split(' '); // Break the line into the name & line number
index.Add(parts[0], Convert.ToInt32(parts[1]));
}
}
然後找到你的文件中的一行,使用方法:
int lineNumber = index["SECTION_B";]; // Convert section name into the line number
long offsetInDataFile = lineMap[lineNumber]; // Convert line number into file offset
然後打開DataFile.txt一個新的FileStream,尋求(offsetInDataFile,SeekOrigin.Begin)移動到的開始行,並使用StreamReader(如上所述)從中讀取行。
謝謝,我擔心在開始操作之前,我將不得不預先處理文件。外部數據庫對我來說不是一種選擇,因爲數據文件變化太頻繁,無論如何,謝謝你的回答 – 2009-05-06 19:25:57
你可能懶惰,只做從開始到你感興趣的部分的預處理。每次訪問從0到那個點將是.Seek():能夠,如果你對後面的部分感興趣,你可以繼續從你離開的地方進行預處理。同時存儲帶有時間戳和任何可識別信息的索引供以後使用(或在數據更新時徹底刪除它)。 – 2009-05-06 19:40:27
我喜歡Pasi的建議,謝謝! – 2009-05-06 19:47:53