【.Net 学习系列】-- FileSystemWatcher 监控文件夹新生成文件,并在确认文件没有被其他程序占用后将其移动到指定文件夹
2024-08-29 07:50:56
监控文件夹测试程序:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace FileSystemWatcherTest
{
class Program
{
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher("C:\\FileSystemWatcher", "*.txt");
watcher.NotifyFilter = NotifyFilters.FileName;
watcher.Created += new FileSystemEventHandler(FileCreated);
watcher.EnableRaisingEvents = true; Console.ReadLine();
} private static void FileCreated(object sender, FileSystemEventArgs e)
{
if (!File.Exists(e.FullPath))
{
return;
}
Console.WriteLine("Created: {0: HH:mm:ss}", DateTime.Now); while (!IsFileReady(e.FullPath))
{
Console.WriteLine("Used: {0: HH:mm:ss}", DateTime.Now);
}
//在这里进行文件处理。。。
Console.WriteLine("Ready: {0: HH:mm:ss}", DateTime.Now); Thread.Sleep( * );
FileInfo fs = new FileInfo(e.FullPath); var moveToPath = @"\\testServer\Shares\" + fs.Name;
fs.MoveTo(moveToPath); if (!File.Exists(moveToPath))
{
Console.WriteLine("Move Faild: {0: HH:mm:ss}", DateTime.Now);
}
Console.WriteLine("Move Success: {0: HH:mm:ss}", DateTime.Now);
} static bool IsFileReady(string filename)
{
FileInfo fi = new FileInfo(filename);
FileStream fs = null;
try
{
fs = fi.Open(FileMode.Open, FileAccess.ReadWrite,FileShare.None);
return true;
} catch (IOException)
{
return false;
} finally
{
if (fs != null)
fs.Close();
}
}
}
}
文件生成测试程序:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace GenerateFileTest
{
class Program
{
static void Main(string[] args)
{
FileStream fs = new FileStream("C:\\FileSystemWatcher\\Test.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fs); var currDateTime = DateTime.Now;
var maxDateTime = currDateTime.AddSeconds(); Console.WriteLine("Log begin: {0}", DateTime.Now.ToString("HH:mm:ss"));
while (currDateTime < maxDateTime)
{
sw.WriteLine(DateTime.Now.ToString());
currDateTime = DateTime.Now;
} //清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close(); Console.WriteLine("Log end: {0}", DateTime.Now.ToString("HH:mm:ss"));
Console.ReadLine();
}
}
}
运行结果:
最新文章
- python PIL比较图片像素
- [SharePoint]SharePoint Claim base Authentication的一个比较好的介绍
- python3 cgi传数据
- ROS笔记——创建简单的主题发布节点和主题订阅节点
- django开发个人简易Blog——数据模型
- iOS NSObject 的 isa 属性的类型 Class
- HDU 4605 Magic Ball Game 树状数组
- java poi导出EXCEL xls文件代码
- Rss 的作用 及使用方法
- linux 机器出现or type control d to continue问题的处理办法
- No.1小白的HTML+CSS心得篇
- VMware装ubuntu 进不去图形界面, 卡在Installing VMware Tools
- cornerstone 怎么使用
- 将非官方扩展程序加入chrome的白名单
- bzoj3944Sum
- MyBridgeWebViewDemo【集成JsBridge开源库的的封装的webview】
- SQL优化 MySQL版 - 多表优化及细节详讲
- JS中的可枚举属性与不可枚举属性以及扩展
- Python中Lambda表达式使用
- nodejs 数据库操作,消息的发送和接收,模拟同步