如何在Windows服务中连续读取文本文件

时间:2014-03-14 13:13:18

标签: c# io windows-services text-files streamreader

我正在阅读Windows服务中的文本文件。根据我的要求,我必须逐行读取文本文件并处理行的内容并插入到数据库中。文本文件的性质是这样的不断更新。有时会在一分钟内添加100行,有时甚至没有。所以没有固定的速率将行插入到文本文件中。 目前我正在使用StreamReader逐行读取文本文件,但是一旦行结束它就会回来。这是我的Windows服务结构。

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的整个结构。如果文本文件中没有下一行可用,那么此读取将停止,并且它将停止,直到服务重新启动,我不想这样做。 那么如果流读取器停止读取行,我该如何检查文件更新。

这是我使用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 Changed Event调用时只读取添加到文本文件中的新行。 请帮忙。

1 个答案:

答案 0 :(得分:1)

创建文件的私有副本,这样文件就可以被其他进程更改。

处理副本。

删除副本。

如果原始文件已更改(可以使用FileSystemWatcher),请重复并且不处理已处理的行。

检测已经处理的行可能是最难的,但取决于系统的幂等性和文件的实际内容。

幂等性意味着您向线路馈送的系统(数据库)在多次传递相同的线路时不会改变。

识别相同的行取决于行的内容。它可能是行号,GUID,ID,时间戳