日期:2014-05-18 浏览次数:21270 次
namespace 文件监控入库 { class Program { static void Main(string[] args) { string MonitorPath; MonitorPath = System.Environment.CurrentDirectory+"\\待入库文件1"; WatcherStrat(@MonitorPath , "*.txt"); Console.ReadKey(); } private static void WatcherStrat(string path, string filter) { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = path; //不知道怎么设置监控多个目录 watcher.Filter = filter; watcher.Created += new FileSystemEventHandler(OnCreated); watcher.EnableRaisingEvents = true; } private static void OnCreated(object source, FileSystemEventArgs e) { //获取程序当前路径和文件列表 string filedir, filepath; string[] filelist; filedir = System.Environment.CurrentDirectory + "\\待入库文件1"; DirectoryInfo dir = new DirectoryInfo(filedir); //实例化directoryInf类 FileSystemInfo[] f = dir.GetFileSystemInfos(); //获取监控目录下的文件名称 filelist = new string[f.Length]; for (int i=0;i<f.Length ;i++) { filelist[i] = filedir + "\\"+f[i].ToString () ; Console.WriteLine(filelist[i]);//输出文件名,调试用的,看正不正常 RedData(filelist[i].ToString ());//相应文件读取函数 } } public static void RedData(string filepath) { //读取单个文件 测试 StreamReader sr = new StreamReader(filepath ); while (sr.ReadLine ()!=null ) { Console .WriteLine (sr.ReadLine ().ToString ()); } sr.Close(); //将读取的资料写入数据库 //............ } public static void CopyFile(string filepath) { //复制转移已入库报文 } } }
public static void RedData(string filepath) { Stream stream; int index = 0; while (true) { try { stream = File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.None); break; } catch (Exception) { if (index++ > 5) { throw; } else { Thread.Sleep(1000); } } } //读取单个文件 测试 StreamReader sr = new StreamReader(stream); string tr = null; while ((tr = sr.ReadLine()) != null) { Console.WriteLine(tr); } sr.Close(); stream.Dispose(); //将读取的资料写入数据库 //............ }