我有一个经常更新的 .csv 文件(大约每分钟 20 到 30 次)。我想将新添加的行写入文件后立即将其插入数据库。
The 文件系统观察者 http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx类监听文件系统更改通知,并在指定文件发生更改时引发事件。问题是 FileSystemWatcher 无法准确确定添加或删除了哪些行(据我所知)。
读取这些行的一种方法是保存并比较更改之间的行数,并读取最后一个和倒数第二个更改之间的差异。然而,我正在寻找一个更干净(也许更优雅)的解决方案。
我写过一些非常相似的东西。我使用 FileSystemWatcher 来获取有关更改的通知。然后,我使用 FileStream 来读取数据(跟踪文件中的最后位置并在读取新数据之前查找该位置)。然后,我将读取的数据添加到缓冲区,该缓冲区会自动提取完整的行,然后输出到 UI。
注意:“this.MoreData(..) 是一个事件,其侦听器添加到上述缓冲区,并处理完整的行提取。
注意:正如已经提到的,只有当修改始终是对文件的添加时,这才有效。任何删除都会导致问题。
希望这可以帮助。
public void File_Changed( object source, FileSystemEventArgs e )
{
lock ( this )
{
if ( !this.bPaused )
{
bool bMoreData = false;
// Read from current seek position to end of file
byte[] bytesRead = new byte[this.iMaxBytes];
FileStream fs = new FileStream( this.strFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
if ( 0 == this.iPreviousSeekPos )
{
if ( this.bReadFromStart )
{
if ( null != this.BeginReadStart )
{
this.BeginReadStart( null, null );
}
this.bReadingFromStart = true;
}
else
{
if ( fs.Length > this.iMaxBytes )
{
this.iPreviousSeekPos = fs.Length - this.iMaxBytes;
}
}
}
this.iPreviousSeekPos = (int)fs.Seek( this.iPreviousSeekPos, SeekOrigin.Begin );
int iNumBytes = fs.Read( bytesRead, 0, this.iMaxBytes );
this.iPreviousSeekPos += iNumBytes;
// If we haven't read all the data, then raise another event
if ( this.iPreviousSeekPos < fs.Length )
{
bMoreData = true;
}
fs.Close();
string strData = this.encoding.GetString( bytesRead );
this.MoreData( this, strData );
if ( bMoreData )
{
File_Changed( null, null );
}
else
{
if ( this.bReadingFromStart )
{
this.bReadingFromStart = false;
if ( null != this.EndReadStart )
{
this.EndReadStart( null, null );
}
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)