【发布时间】:2018-11-10 00:44:50
【问题描述】:
我有一个用 Borland Delphi 编写的旧本机应用程序:
应用程序与特殊硬件接口,并在.db 文件中的 BDE/Borland Paradox 数据库中创建/存储其数据。我不是此应用程序的作者,创建它的公司早已不复存在。
我需要向这个应用程序添加一些自定义功能,即当某个硬件相关事件发生时能够读取数据库。我找到了一个旧的 C 库,它允许我读取悖论 .db 文件。所以这部分被覆盖了。
我现在想要完成的是找到一种方法来跟踪此应用程序写入其.db 文件的时刻。所以我决定在我的测试应用程序中尝试以下内容:
static void Main(string[] args)
{
string path = "C:\\Program Files\\Company Name\\logfile.db";
string strDirName = Path.GetDirectoryName(path);
string strFileName = Path.GetFileName(path);
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = strDirName;
watcher.NotifyFilter = NotifyFilters.Attributes |
NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastAccess |
NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
watcher.Filter = strFileName; // "*.db";
watcher.IncludeSubdirectories = false;
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.Error += new ErrorEventHandler(OnError);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Starting the watch...");
Console.WriteLine("Folder: " + watcher.Path);
Console.WriteLine("File: " + watcher.Filter);
while (true)
{
watcher.WaitForChanged(WatcherChangeTypes.All);
Console.WriteLine("-next-");
}
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("-\"" + e.FullPath + "\", type=" + e.ChangeType + ", time=" + DateTime.Now);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("-\"{0}\" renamed to \"{1}\"", e.OldFullPath, e.FullPath);
}
private static void OnError(object source, ErrorEventArgs e)
{
Console.WriteLine("#error: \"" + e.ToString() + "\", time=" + DateTime.Now);
}
问题是它似乎没有看到对数据库的任何更改。
如果我通过在记事本中打开 .txt 文件对其进行测试,然后通过一些更改保存它,它可以正常工作。但不是我需要的应用程序。
这是我知道它不起作用的原因:
相关应用程序已在运行。
我在它旁边启动我的应用程序。它没有显示错误或异常。所以我知道我的
watcher.WaitForChanged函数已经启动了。我等待在相关应用程序中注册硬件事件。
我的测试应用没有发现任何变化。
然后我复制
logfile.db文件,同时应用程序和我的测试应用程序仍在运行,然后在我的笔记本电脑中使用 Paradox DB 查看器打开它。它会显示数据库中的新条目。
那么为什么FileSystemWatcher 没有发现logfile.db 文件被更改?
PS。我在 64 位版本的 Windows 7 Pro 上完成所有这些操作。
【问题讨论】:
-
文件的 LastWrite 是否发生变化?
-
目录条目保证只有在句柄关闭时才会更新。 FileSystemWatcher 查找目录条目更改。
-
@RaymondChen:那么在这种情况下,我还有什么其他选择来跟踪变化? (我不想在重复计时器上读取/轮询该数据库文件。)
标签: c# .net file-watcher bde paradox