とても似たようなことを書いています。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 );
}
}
}
}
}