将数据附加到文件时更新Listview
本文关键字:更新 Listview 文件 数据 | 更新日期: 2023-09-27 18:21:25
以下是我正在做的事情:我正在将消息和日期时间记录到一个文本文件中,我成功地做到了这一点。现在,我想将其添加到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;
为该文件夹中的所有文件的更改事件添加事件处理程序:
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);
}
当发生更改时,您需要自己获得更改
并将其添加到您想要的控件中
例如,您可以在更改之前获取文件内容并将其存储然后在发生变化后获取并比较
希望我能帮助