![](/img/trans.png)
[英]How to parse a text file with alternating lines of names and lists of integers?
[英]How to monitor a text file and parse new lines?
我想知道是否有一種方法可以在不鎖定 .txt 文件的情況下對其進行監視,並解析新附加的行以便將其發送到數據庫。
我知道FileSystemWatcher
將監視 txt 文件而不鎖定它並在發生更改時通知我。 問題是它沒有告訴已附加的數據行。 我看過的所有示例都排除了顯示新附加行或對新數據進行任何處理的部分。 我的程序具有以下結構:
static void Main(string[] args)
{
//string line;
//createWatcher (FileSystemWatcher)
foreach (string line in getLines(@"C://Documents/log.txt"))
{
string teststring = line;
string[] parts = line.Split(' ', ',', '-', '>', '[', ']');
StringBuilder builder = new StringBuilder();
foreach (string h in parts)
{
builder.Append(h).Append(" ");
}
string result = builder.ToString();
string cleanedString = System.Text.RegularExpressions.Regex.Replace(result, @"\s+", " ");
string trimString = cleanedString.Trim();
trimString = trimString.Remove(trimString.Length - 7);
//Console.WriteLine(trimString);
//Process new lines (parse/split)
//Connect and send to database
}
}
所以我的目標是監視 .txt 文件而不鎖定它。
有誰知道如何最好地解決這個問題? 或者有好的教程?
最好的辦法是讓文件系統觀察器觸發的代碼跟蹤讀取文件的流中的Position
。 這是一些偽代碼:
if(no stored position)
start at beginning of file
else
{
streamOfFile.Seek(storedPosition)
read until end of file
store stream.Postition
}
這可以通過跟蹤上次讀取文件的長度來完成,然后下次從該點開始。 但是,圍繞此存在很多競爭條件,因為您可能在操作系統寫入的同時從文件中讀取。
您不能保證對文件的唯一更改是追加,這不是您的更大問題嗎? 如果我在文件頂部插入一行或替換整個內容會怎樣?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.