当前位置: 开源爱好者 » 编程教程 » C#教程 » 正文

C#监视文件并弹出提示信息

C#监视文件并添加文件提示功能:

private void button14_Click(object sender, EventArgs e)
{//监视文件创建删除操作
    //配置文件系统监视器FileSystemWatcher
    var MyWatch = new System.IO.FileSystemWatcher();
    MyWatch.Path = Application.StartupPath;
    MyWatch.Filter = "*.*";
    MyWatch.IncludeSubdirectories = true;
    //添加文件系统监视器FileSystemWatcher事件句柄
    MyWatch.Created += new System.IO.FileSystemEventHandler(OnCreatedOrDeleted);
    MyWatch.Deleted += new System.IO.FileSystemEventHandler(OnCreatedOrDeleted);
    MyWatch.EnableRaisingEvents = true;
    if (System.IO.File.Exists("MyTestFile.txt"))
        System.IO.File.Delete("MyTestFile.txt");
    var MyStream = new System.IO.FileStream("MyTestFile.txt", System.IO.FileMode.Create);
    MyStream.Close();
}
private static void OnCreatedOrDeleted(object sender, System.IO.FileSystemEventArgs e)
{//创建和删除文件时显示提示信息
    var MyInfo = e.FullPath + "文件已经被成功";
    switch (e.ChangeType)
    {
        case System.IO.WatcherChangeTypes.Created:
            MyInfo += "创建!";
            break;
        case System.IO.WatcherChangeTypes.Deleted:
            MyInfo += "删除!";
            break;
    }
    MessageBox.Show(MyInfo, "信息提示", MessageBoxButtons.OK);
}

CopyRight 2015© 开源爱好者 All Rights Reserved 豫ICP备16030607号 隐私声明 网站地图