这就是我在做的事情: 我正在将消息和日期时间记录到我成功完成的文本文件中。现在我想将它添加到Listview(或任何其他可用于实现此目的的控件),同样在文件更新时应更新Listview。
我是c#的新手,所以请原谅我缺乏知识。
答案 0 :(得分:3)
您可以使用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
}
}
答案 1 :(得分:1)
我认为您保存了在代码中所做的更改
然后你需要观察文件发生变化的时间
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);
}
当发生变化时,您需要自己进行更改 并将其添加到您想要的控件
您可以在更改和存储之前获取文件内容 然后在发生变化后得到它并进行比较
希望我帮助