如何在Windows服务中连续读取文本文件
本文关键字:连续 读取 取文本 文件 服务 Windows | 更新日期: 2023-09-27 17:50:26
我正在阅读windows服务中的文本文件。根据我的要求,我必须逐行读取文本文件并处理行内容并插入数据库。文本文件的性质决定了它是不断更新的。有时在一分钟内会增加100行,有时没有。因此,插入文本文件的行数没有固定的速率。目前,我正在使用StreamReader
逐行读取文本文件,并使用while循环,但一旦行结束,它就会回来。这是我的windows Service的结构。
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
private System.Threading.Thread _thread;
private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
public void OnDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
_thread = new Thread(parseAndProcess);
_thread.Start();
}
public void parseAndProcess()
{
if (System.IO.File.Exists(FileToCopy) == true)
{
using (StreamReader reader = new StreamReader(FileToCopy))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line != "")
{
//line processing logic goes here
}
reader.Close();
}
}
}
}
protected override void OnStop()
{
_shutdownEvent.Set();
_thread.Join(); // wait for thread to stop
}
}
}
这是我的windows Service的整个结构。在这里,如果文本文件中没有下一行可用,则读取将停止,直到服务重新启动,这是我不想做的。那么我如何检查文件更新,以防streamreader停止读取行。
这是我更新的代码与FileSystemWatcher
protected override void OnStart(string[] args)
{
_thread = new Thread(parseAndProcess);
_thread.Start();
FileSystemWatcher Watcher = new FileSystemWatcher("File Path");
Watcher.EnableRaisingEvents = true;
Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
}
// This event is raised when a file is changed
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
_thread = new Thread(parseAndProcess);
_thread.Start();
}
在这段代码中,我有一个疑问,我将如何读取仅添加到文本文件中的新行,当被FileSystemWatcher更改事件调用时。请帮助。
创建一个文件的私有副本,这样文件就可以被其他进程打开。
处理副本。
删除副本。
如果原始文件已经更改(可以使用FileSystemWatcher),重复并且不处理已经处理过的行。
检测已经处理过的行可能是最难的,但这取决于系统的等幂性和文件的实际内容。
等幂意味着当你多次传递同一行时,你输入的系统(数据库)不会改变。
识别同一行取决于该行的内容。可以是行号,GUID, ID,时间戳