开发者

Im trying to raise a event when a file is updated in C#

i know this code dont work but is describe开发者_运维百科s good what im trying to do, i want to run the code inside the if check when Lastwritetime is greater then oldvalue date.

private void timer1_Tick(object sender, EventArgs e)
{
    DateTime lastWriteTime = File.GetLastWriteTime(@"C:\temp\test_folder\TestFile.txt");

    if (lastWriteTime.ToString() > oldValue.ToString())
    {
        MessageBox.Show("Succsess");
    }
    string oldValue = lastWriteTime.ToString();
}

edit: im not using SystemfileWatcher because of the mulitple events raised on change.


Try a FileSystemWatcher instead.

Listens to the file system change notifications and raises events when a directory, or file in a directory, changes.


Why are you comparing string representations? If oldValue is DateTime as well, just compare them as is:

if(lastWriteTime.ToString() > oldValue)
    // ...

Plus, make sure that the scope of oldValue is greater than the scope of timer1_Tick (that is, ensure that it's a class member variable).

And of course, do not reinvent the wheel: FileSystemWatcher.


Consider the FileSystemWatcher class. It works pretty well.

One thing to be wary of, however, is that there can be issues with these when trying to monitor files that are network mounted, at least there were in .NET 2.0. We found that they could fail if the network connection got interrupted for some amount of time.


Check out the FileSystemWatcher class. It can monitor files and raises an event when they change.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜