多线程监控文件夹,FlieSystemWatcher,并使用共享函数

懒人想做的事 2011-01-06 09:55:47
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using System.Collections;

namespace Thread_FileSystemWatcher
{
class Program
{
private static Thread[] threads;
private static string[] pPath;

static void Main(string[] args)
{
threadsPEIZHI();
while (Console.Read() != 'q') ;

}

static void threadsPEIZHI()
{
try
{
pPath = new string[2];
pPath[0] = "c:\\";
pPath[1] = "e:\\";

threads = new Thread[pPath.Length];
for (int i = 0; i <= threads.Length-1; i++)
{
threads[i] = new Thread(Run);
threads[i].Name = pPath[i];
threads[i].Start();
Console.WriteLine(threads[i].Name);
}
}
catch(Exception Ex)
{
Console.WriteLine(Ex.Message);
}
}

static void Run()
{
Run(Thread.CurrentThread.Name);
}

static void Run(string pPath)
{
FileSystemWatcher fsw = new FileSystemWatcher(pPath);
fsw.Filter = "*.*";//监控所有类型,包括子文件夹
fsw.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.LastAccess | NotifyFilters.LastWrite;

fsw.Changed += new FileSystemEventHandler(OnChanged);
fsw.Created += new FileSystemEventHandler(OnCreated);
fsw.Deleted += new FileSystemEventHandler(OnDeleted);
fsw.Renamed += new RenamedEventHandler(OnRenamed);

fsw.EnableRaisingEvents = true;//开启监控

}

static void OnChanged(object source,FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}

static void OnCreated(object source,FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}

static void OnDeleted(object source,FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}

static void OnRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}

}
}

请指教!
...全文
389 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
NET小z 2011-08-17
  • 打赏
  • 举报
回复
如果一发生变化,会重复好几次的触发OnChanged这个事件,建议你看看这个
http://hi.baidu.com/84845357/blog/item/004f9d9289e77386a877a425.html
HolyPlace 2011-01-06
  • 打赏
  • 举报
回复
很好很强大
aspnetchengxuyuan 2011-01-06
  • 打赏
  • 举报
回复
意思为对文件一旦有了操作就在控制台上显示路径神马的滴吧!委托的问题,再看看先...
懒人想做的事 2011-01-06
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 wuyq11 的回复:]
什么问题
[/Quote]
我想看看其他人的方法。
懒人想做的事 2011-01-06
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 bdmh 的回复:]
看来楼主是绝世高人啊,说话都不一样
[/Quote]
看来我说话确实要改进。刚刚来csdn.多谢指教啊。
wuyq11 2011-01-06
  • 打赏
  • 举报
回复
什么问题
懒人想做的事 2011-01-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 lost_painting 的回复:]
指教什么?
问题还是说我们来围观你的代码,提出意见?
还是说你推荐一个方法给我们,我们参考?
[/Quote]

看来这样会被误读啊。只是对,提意见。或其它方法。
bdmh 2011-01-06
  • 打赏
  • 举报
回复
看来楼主是绝世高人啊,说话都不一样
鸭梨山大帝 2011-01-06
  • 打赏
  • 举报
回复
指教什么?
问题还是说我们来围观你的代码,提出意见?
还是说你推荐一个方法给我们,我们参考?

111,096

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧