[英]C# writing to file in quick succession using FileWatcher OnCreated event
[英]C# FileWatcher File not free after reading
我刚开始使用C#,并尝试创建一个FileWatcher,如果更改了文件,它应该打印文件的内容:
{
public static void watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "Path";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "Filter";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
public static void OnChanged(object source, FileSystemEventArgs e)
{
using (TextReader r = File.OpenText("Path")) {
while ((s = r.ReadLine()) != null) {
Console.WriteLine(s);
}
r.Close();
}
}
static void Main()
{
watch();
}
}
到目前为止,FileWatcher可以正常工作,但是如果我尝试打印内容,则它可以工作一次,无论我等待多长时间,程序都将停止进行第二次更改。 据我了解,“ using”语句应释放文件。 close命令完全不会更改任何内容。
该文件是非常小的文本文件,应该没有问题。
是否有任何强制程序释放文件的方法?
我认为不是watcher.EnableRaisingEvents = true
,在您的情况下想使用watcher.WaitForChanged(WatcherChangeTypes.All)
来使您的程序无限期地等待更改。
顺便说一句, r.Close()
语句是多余的,因为您已经通过using
隐式调用Dispose()
,而后者又调用Close()
。
编辑:要更具体: WaitForChanged
当然只是等待一个更改,然后返回,因此,如果要等待更多更改,则可以使用循环。 请注意,如果以这种方式使用它,则不需要事件处理程序。
while(true)
{
watcher.WaitForChanged(WaitForChanged.All);
// Do stuff with the changed file here, no event handler needed
using(var sr = new StreamReader(filePath))
{
// ...
}
}
首先要做的是调试并验证您的方法OnChanged
是否仅被调用一次,或者是否在受监视文件的以下编辑中被调用,那么您已经知道问题出在监视者的生命周期/范围还是其他地方。
这是控制台应用程序吗? 调用main中的watch方法后,它关闭还是保持打开状态?
以下代码可以正常工作:
using System;
using System.IO;
namespace FileReadTest
{
internal class Program
{
public static FileSystemWatcher watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "d:\\";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "test.txt";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
return watcher;
}
public static void OnChanged(object source, FileSystemEventArgs e)
{
string s;
using (StreamReader r = new StreamReader(File.Open("d:\\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
while ((s = r.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
static void Main()
{
var watcher = watch();
Console.ReadKey();
watcher.Dispose();
}
}
}
请注意,我已更改文件读取例程,以避免在其他程序打开文件时出现一些读取问题。 FileSystemWatcher
也不会超出范围,不会被意外处置。
您需要处置FileSystemWatcher。
public static void OnChanged(object source, FileSystemEventArgs e)
{
using (TextReader r = File.OpenText("Path")) {
while ((s = r.ReadLine()) != null) {
Console.WriteLine(s);
}
r.Close();
}
File((FileSystemWatcher)sender).Dispose();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.