以下是我在做什麼: 我正在將消息和日期時間記錄到我成功完成的文本文件中。現在我想將它添加到Listview(或任何其他可用於實現此目的的控件)中,並且在更新文件時應該更新Listview。將數據附加到文件時更新列表視圖?
我是新來的c#所以原諒我缺乏知識。
以下是我在做什麼: 我正在將消息和日期時間記錄到我成功完成的文本文件中。現在我想將它添加到Listview(或任何其他可用於實現此目的的控件)中,並且在更新文件時應該更新Listview。將數據附加到文件時更新列表視圖?
我是新來的c#所以原諒我缺乏知識。
您可以使用FileSystemWatcher的
實例化一個FileSystemWatcher對象:
FileSystemWatcher watcher= new FileSystemWatcher();
watcher.Path = @"c:\folder_that_contains_log_file";
設置通知過濾器:什麼事件應觀察
watcher.NotifyFilter= NotifyFilters.LastWrite | NotifyFilters.FileName;
指定的FileWatcher可以引發事件:
watcher.EnableRaisingEvents = true;
change事件添加事件處理程序從該文件夾中的所有文件:
watcher.Changed += new FileSystemEventHandler(Changed);
捕獲更改事件:
private void Changed(object sender, FileSystemEventArgs e)
{
// Get the ful path of the file that changed and rised this change event
string fileThatChanged = e.FullPath.ToString();
//Check if file that changed is your log file
if (fileThatChangedPath.equals("path_tot_the_log_file"))
{
// clear items from ListView
// Read from file line by line
// Add each line to the ListView
}
}
我認爲您保存您在代碼中所做的更改
那麼你將需要觀察文件發生何種變化時
FileSystemWatcher watch;
public Load()
{
watch = new FileSystemWatcher();
watch.Path = @"C:\tmp";
watch.NotifyFilter = NotifyFilters.LastWrite;
// Only watch text files.
watch.Filter = "*.txt";
watch.Changed += new FileSystemEventHandler(OnChanged);
watch.EnableRaisingEvents = true;
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
if (e.FullPath == @"C:\tmp\link.txt")
MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
}
發生10次
修改時,您將需要得到你自己
的變化,並把它添加到你想要
控制可以例如改變之前獲取文件內容,並將其存儲 然後讓它發生變化後比較一下
希望我幫忙
謝謝。有沒有一種方法可以將Listview控件綁定到這個文件,它會照顧它而不是使用filesystemwatcher? – Ash24
非常感謝。我在同一個方向思考。但有沒有一種方法可以將Listview控件綁定到該文件,並且它會照顧它而不是使用filesystemwatcher? – Ash24
@ Ash24我認爲沒有這個機制.. –
好的沒問題。感謝您的幫助。 – Ash24