c# – 如何等到File.Exists?
发布时间:2020-12-15 06:27:33 所属栏目:百科 来源:网络整理
导读:我有一个应用程序,在所选文件夹中监听* .log文件.我使用FileSystemWatcher. 但是有一个问题.负责制作该文件的其他应用程序需要以下步骤: 制作一个* .gz文件 解压缩到txt文件(一些随机文件名) 将* .txt名称更改为* .log扩展名. 我不能改变这种行为. 所以我为
我有一个应用程序,在所选文件夹中监听* .log文件.我使用FileSystemWatcher.
但是有一个问题.负责制作该文件的其他应用程序需要以下步骤: >制作一个* .gz文件 我不能改变这种行为. 所以我为* .gz和* .txt文件制作了2个FileSystemWatchers.为什么?因为这个应用程序有时不解压缩gz文件,有时不会将txt文件重命名为最终的* .log文件. FileSystemWatcher2捕获txt文件,然后(在大多数情况下,它被重命名以在下一个1000ms内登录)我需要等待一些时间来检查txt文件是否存在(如果没有,它似乎被重命名为最终的* .log文件) . 问题是,如果没有Thread.Sleep()来检查文件是否存在,以防止UI冻结? 我希望很清楚,如果不是我会尝试更好的描述它.我认为这是一个复杂的问题. 一些代码示例: gz文件的守望者 private void fileSystemWatcher_Created(object sender,FileSystemEventArgs e) { //this is for gz files in case if gz file is not unpacked automatically by other app //I need to wait and check if gz was unpacked,if not,unpack it by myself,//then txt watcher will catch that Thread.Sleep(5000); if (File.Exists(e.FullPath)) { try { byte[] dataBuffer = new byte[4096]; using (System.IO.Stream fs = new FileStream(e.FullPath,FileMode.Open,FileAccess.Read)) { using (GZipInputStream gzipStream = new GZipInputStream(fs)) { string fnOut = Path.Combine(path_to_watcher,Path.GetFileNameWithoutExtension(e.FullPath)); using (FileStream fsOut = File.Create(fnOut)) { StreamUtils.Copy(gzipStream,fsOut,dataBuffer); } } } } catch { //Ignore } } } txt文件的监视器: private void fileSystemWatcher2_Created(object sender,FileSystemEventArgs e) { //this is for txt file Thread.Sleep(3500); if (File.Exists(e.FullPath)) { //make my actions } else { //make my actions } } 解决方法
实际上FileSystemWatcher创建的事件由.NET本身在单独的线程中调用.所以基本上你需要做任何事情.你的代码是好的,因为它是.
这是证明: class Program { static void Main(string[] args) { FileSystemWatcher fw = new FileSystemWatcher(@"C:temp"); fw.Created += fileSystemWatcher_Created; Console.WriteLine(Thread.CurrentThread.ManagedThreadId); fw.EnableRaisingEvents = true; Console.ReadLine(); } static void fileSystemWatcher_Created(object sender,FileSystemEventArgs e) { Console.WriteLine(Thread.CurrentThread.ManagedThreadId); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |