CommandHandler;Fields#regionFieldsprivatestringfileName;privateFileSystemWatcherwatcher;privateSystem." />

亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

C#中利用FileSystemWatcher對(duì)單個(gè)文件內(nèi)容的監(jiān)視

系統(tǒng) 2655 0

在項(xiàng)目中需要用 FileSystemWatcher對(duì)單個(gè)文件內(nèi)容進(jìn)行監(jiān)視,文件中每添加一行則需要Fire相應(yīng)的事件,代碼如下

??? public ? class ?CommandWatcher
????
{


????????
public ? event ?EventHandler < CommandEventArgs > ?CommandHandler;
??????

????????
Fields ?Fields


????????
public ?CommandWatcher( string ?cmdfile)
????????
{
????????????
this .fileName? = ?cmdfile;
????????????isChangeImmediate?
= ? true ;

?????????
????????}




????????
????????
//
????????
// ?Summary:
????????
// ?????Raises?the?System.IO.FileSystemWatcher.Changed?event.
????????
//
????????
// ?Parameters:
????????
// ???e:
????????
// ?????A?System.IO.FileSystemEventArgs?that?contains?the?event?data.
???????? protected ? void ?OnChanged( object ?sender,?FileSystemEventArgs?e)???
????????
{
????????????ReloadFile();
????????}



????
????????
//
????????
// ?Summary:
????????
// ?????Raises?the?System.IO.FileSystemWatcher.Error?event.
????????
//
????????
// ?Parameters:
????????
// ???e:
????????
// ?????An?System.IO.ErrorEventArgs?that?contains?the?event?data.
???????? protected ? void ?OnError( object ?sender,?ErrorEventArgs?e)
????????
{

????????}


????????
//
????????
// ?Summary:
????????
// ?????Raises?the?System.IO.FileSystemWatcher.Renamed?event.
????????
//
????????
// ?Parameters:
????????
// ???e:
????????
// ?????A?System.IO.RenamedEventArgs?that?contains?the?event?data.
???????? protected ? void ?OnRenamed( object ?sender,?RenamedEventArgs?e)
????????
{

????????}




????????
/// ? <summary>
????????
/// ?Hook?up?for?the?currently?selected?monitoring?method.
????????
/// ? </summary>

???????? public ? void ?Start()
????????
{
????????????
if ?(isChangeImmediate)
????????????
{
????????????????
// ?stop?timer?if?running
????????????????ClearTimer();
????????????????
// ?If?a?file?is?set?and?the?watcher?has?not?been?set?up?yet?then?create?it
???????????????? if ?( null ? != ?fileName? && ? null ? == ?watcher)
????????????????
{
????????????????????
string ?path? = ?Path.GetDirectoryName(fileName);
????????????????????
string ?baseName? = ?Path.GetFileName(fileName);
????????????????????
// ?Use?the?FileSystemWatcher?class?to?detect?changes?to?the?log?file?immediately
????????????????????
// ?We?must?watch?for?Changed,?Created,?Deleted,?and?Renamed?events?to?cover?all?cases
????????????????????watcher? = ? new ?System.IO.FileSystemWatcher(path,?baseName);
????????????????????FileSystemEventHandler?handler?
= ? new ?FileSystemEventHandler(OnChanged);
????????????????????watcher.Changed?
+= ?handler;
????????????????????watcher.Created?
+= ?handler;
????????????????????watcher.Deleted?
+= ?handler;
????????????????????watcher.Renamed?
+= ?OnRenamed;
????????????????????
// ?Without?setting?EnableRaisingEvents?nothing?happens
????????????????????watcher.EnableRaisingEvents? = ? true ;
????????????????}

????????????}

????????????
else
????????????
{
????????????????
// ?On?a?timer?so?clear?the?watcher?if?previously?set?up
????????????????ClearWatcher();
????????????????
int ?numSeconds? = ? 5 ;
???????????????
????????????????
if ?( null ? != ?timer)
????????????????
{
????????????????????
// ?Timer?is?already?running?so?just?make?sure?the?interval?is?correct
???????????????????? if ?(timer.Interval? != ? 1000 ? * ?numSeconds)
????????????????????
{
????????????????????????timer.Interval?
= ? 1000 ? * ?numSeconds;
????????????????????}

????????????????}

????????????????
else
????????????????
{
????????????????????
// ?Fire?up?a?timer?if?the?user?entered?a?valid?time?interval
???????????????????? if ?( 0 ? != ?numSeconds)
????????????????????
{
????????????????????????timer?
= ? new ?System.Windows.Forms.Timer();
????????????????????????timer.Interval?
= ? 1000 ? * ?numSeconds;
????????????????????????timer.Tick?
+= ?timerTick;
????????????????????????timer.Start();
????????????????????}

????????????????}

????????????}

????????????
this .ReloadFile();
????????}


????????
void ?timerTick( object ?sender,?EventArgs?e)
????????
{
????????????UpdateBasedOnFileTime();
????????}



????????
/// ? <summary>
????????
/// ?Update?the?log?file?if?the?modified?timestamp?has?changed?since?the?last?time?the?file?was?read.
????????
/// ? </summary>

???????? private ? void ?UpdateBasedOnFileTime()
????????
{
????????????
if ?( null ? != ?fileName)
????????????
{
????????????????
// ?This?returns?"12:00?midnight,?January?1,?1601?A.D."?if?the?file?does?not?exist
????????????????DateTime?newLastModifiedTime? = ?File.GetLastWriteTime(fileName);
????????????????
if ?((newLastModifiedTime.Year? < ? 1620 ? && ?newLastModifiedTime? != ?lastModifiedTime)
????????????????????
|| ?newLastModifiedTime? > ?lastModifiedTime)
????????????????
{
????????????????????
// OnLogFileChanged();
????????????????????ReloadFile();
????????????????}

????????????}

????????}

????????
/// ? <summary>
????????
/// ?Read?the?log?file.
????????
/// ? </summary>
????????
/// ? <remarks> If?the?user?has?some?text?selected?then?keep?that?text?selected. </remarks>

???????? private ? void ?ReloadFile()
????????
{
????????????
if ?(reloadingFile)? return ;? // ?already?busy?doing?this
????????????reloadingFile? = ? true ;
????????????
try
????????????
{
????????????????
if ?( null ? == ?fileName)
????????????????
{
???????????????????
// ?textBoxContents.Text?=?"";
????????????????}

????????????????
else
????????????????
{
????????????????????
string ?newFileLines? = ? "" ;
????????????????????lastModifiedTime?
= ?File.GetLastWriteTime(fileName);? // ?Remember?when?we?last?read?in?this?file
???????????????????? long ?newLength? = ? 0 ;?? // ?will?be?set?properly?later?if?all?is?well
???????????????????? bool ?fileExists? = ?File.Exists(fileName);
????????????????????
bool ?needToClear? = ? ! fileExists;
????????????????????
if ?(fileExists)
????????????????????
{
????????????????????????
// ?It?is?possible?the?file?will?be?in?use?when?we?read?it?(especially?if?using?Immediate?mode)
????????????????????????
// ?So,?we?will?try?up?to?5?times?to?access?the?file
???????????????????????? int ?count? = ? 0 ;
????????????????????????
bool ?success? = ? false ;
????????????????????????
while ?(count? < ? 5 ? && ? ! success)
????????????????????????
{
????????????????????????????
try
????????????????????????????
{
????????????????????????????????
// ?Open?with?the?least?amount?of?locking?possible
???????????????????????????????? using ?(FileStream?stream? = ?File.Open(fileName,?FileMode.Open,?FileAccess.ReadWrite,?FileShare.ReadWrite))
????????????????????????????????
{
????????????????????????????????????newLength?
= ?stream.Length;
????????????????????????????????????
if ?(newLength? >= ?lastFileSize)
????????????????????????????????????
{
????????????????????????????????????????stream.Position?
= ?lastFileSize;?? // ?Only?read?in?new?lines?added
????????????????????????????????????}

????????????????????????????????????
else
????????????????????????????????????
{
????????????????????????????????????????needToClear?
= ? true ;
????????????????????????????????????}

????????????????????????????????????
using ?(StreamReader?reader? = ? new ?StreamReader(stream))
????????????????????????????????????
{
????????????????????????????????????????newFileLines?
= ?reader.ReadToEnd();

????????????????????????????????????????
if ?(newFileLines? != ? string .Empty)
????????????????????????????????????????
{
????????????????????????????????????????????
if ?( this .CommandHandler? != ? null )
????????????????????????????????????????????????
this .CommandHandler( this ,? new ?CommandEventArgs(newFileLines));
????????????????????????????????????????}

??????????????????????????????????????
????????????????????????????????????????
// string?[]tmp?=?newFileLines.Split(seprater,?StringSplitOptions.RemoveEmptyEntries);

????????????????????????????????????}

????????????????????????????????}

????????????????????????????????success?
= ? true ;
????????????????????????????}

????????????????????????????
catch ?(IOException)
????????????????????????????
{
????????????????????????????????System.Threading.Thread.Sleep(
50 );? // ?Give?a?little?while?to?free?up?file
????????????????????????????}

????????????????????????????
++ count;
????????????????????????}

????????????????????}

????????????????????
// ?Remember?the?current?file?length?so?we?can?read?only?newly?added?log?lines?the?next?time?the?log?file?is?read
????????????????????lastFileSize? = ?newLength;
????????????????????
if (lastFileSize? > ? 1024 ? * ? 1024 ? * ? 2 )
????????????????????
{
????????????????????????File.Delete(fileName);
????????????????????????File.Create(fileName);
????????????????????}
???????????????????
???????????????
????????????????????
if ?( 0 ? != ?newFileLines.Length)
????????????????????
{
????????????????????????
// ?See?if?this?log?file?has?proper?cr/lf?and?if?not?convert
???????????????????????? int ?lastCr? = ?newFileLines.LastIndexOf( ' \n ' );
????????????????????????
if ?( - 1 ? != ?lastCr? && ? 0 ? < ?lastCr)
????????????????????????
{
????????????????????????????
if ?(newFileLines[lastCr? - ? 1 ]? != ? ' \r ' )
????????????????????????????
{
????????????????????????????????
// ?OK,?this?file?only?has?Cr?and?we?need?to?convert?to?CrLf
????????????????????????????????newFileLines? = ?newFileLines.Replace( " \n " ,? " \r\n " );
????????????????????????????}

????????????????????????}

????????????????????}

????????????????????
???????????????????
????????????????}

????????????}

????????????
finally
????????????
{
????????????????
// ?Put?clearing?this?flag?in?a?finally?so?we?know?it?will?be?cleared
????????????????reloadingFile? = ? false ;
????????????}

????????}



????????
/// ? <summary>
????????
/// ?Cleanup?the? <see?cref="Timer"/>
????????
/// ? </summary>

???????? private ? void ?ClearTimer()
????????
{
????????????
if ?( null ? != ?timer)
????????????
{
????????????????timer.Tick?
-= ?timerTick;
????????????????timer.Dispose();
????????????????timer?
= ? null ;
????????????}

????????}


????????
/// ? <summary>
????????
/// ?Cleanup?the? <see?cref="FileSystemWatcher"/>
????????
/// ? </summary>

???????? private ? void ?ClearWatcher()
????????
{
????????????
if ?( null ? != ?watcher)
????????????
{
????????????????FileSystemEventHandler?handler?
= ? new ?FileSystemEventHandler(OnChanged);
????????????????watcher.Changed?
-= ?handler;
????????????????watcher.Created?
-= ?handler;
????????????????watcher.Deleted?
-= ?handler;
????????????????watcher.Renamed?
-= ?OnRenamed;
????????????????watcher.Dispose();
????????????????watcher?
= ? null ;
????????????}

????????}




????}

C#中利用FileSystemWatcher對(duì)單個(gè)文件內(nèi)容的監(jiān)視


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長(zhǎng)會(huì)非常 感謝您的哦?。?!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 亚洲欧美精品综合中文字幕 | 亚洲日本香蕉视频 | 精品国产呦系列在线看 | 亚洲精品成人中文网 | 免费看黄色片视频 | 国产精品人伦久久 | 在线性爱视频 | 色黄网站青青草原免费 | 成人毛片全部免费观看 | 亚洲瑟瑟网 | 久久国产精品影院 | 伊人伊网| 黑人和黑人激情一级毛片 | 亚洲一级毛片在线播放 | 久草在线观看首页 | 热99re久久国超精品首页 | 国产乱人伦偷精品视频不卡 | 亚洲欧洲中文日产 | 青青青草国产 | 亚洲国产欧美久久香综合 | 亚洲精品高清在线一区二区三区 | 欧美三级做爰视频 | 精品色综合 | 亚洲欧美日韩国产一区图片 | 国产日韩欧美在线观看不卡 | 无遮挡一级毛片视频 | 九九热视频这里只有精品 | 四虎影视亚洲精品 | 综合在线视频精品专区 | 国产区二区 | 高清欧美日本视频免费观看 | 91粉嫩萝控精品福利网站 | 亚洲第一区二区快射影院 | 亚洲夂夂婷婷色拍ww47 | 久久久久久不卡 | 在线精品一区二区三区 | 99免费| 久久国产精品久久久久久久久久 | 天天干干干干 | 亚洲欧美日韩专区一 | 亚洲欧美精品中字久久99 |