Windows应用程序中的FileSystemWatcher问题 [英] FileSystemWatcher issue in windows application

查看:76
本文介绍了Windows应用程序中的FileSystemWatcher问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的朋友,

我有一个Windows应用程序,它正在使用filesystemwatcher来侦听该文件夹,并且一旦创建xml文件,它将解析该文件并将其插入数据库.

问题是创建第一个文件时工作正常,创建第二个文件时它显示错误该进程无法访问该文件,因为该文件正在被另一个进程使用".

我无法处理filesystemwatcher对象,因为它应始终侦听该文件夹.

我已经在下面发布了代码.请帮助我解决问题.

Dear Friends,

I have a windows application which is using a filesystemwatcher which listens to the folder and when ever the xml file created, it will parse the file and inserts to the database.

The problem is it works fine when the first file is created, and when the second file created, it shows error, "The process cannot access the file because it is being used by another process".

I cannot dispose the filesystemwatcher object because it should listen to the folder always.

I have posted the code below. Kindly help me to resolve the issue.

private void button1_Click(object sender, EventArgs e)
        {
            ListenToFolder(@"F:\EscherData\");
        }

        private void ListenToFolder(string path)
        {
            try
            {

                    FileSystemWatcher fs = new FileSystemWatcher(path);

                    fs.IncludeSubdirectories = false;


                    fs.Created += new FileSystemEventHandler(OnFileCreate);


                    fs.EnableRaisingEvents = true;





            }
            catch (Exception e)
            {

                //MessageBox.Show(e.ToString());
            }
        }

        private void OnFileCreate(object e, FileSystemEventArgs ev)
        {

            try
            {

                ReadXmlData(ev.FullPath);


            }
            catch (Exception ex)
            {
               MessageBox.Show(ex.ToString());
            }






        }

推荐答案

问题是FileSystemWatcher会立即告诉您文件的创建时间.它不等待文件被释放.当您已经收到消息时,系统仍在创建文件,这就是为什么您收到该错误消息的原因.基本上,您需要等待.参加活动,然后让实用程序监视该文件,直到可以免费读取为止.这是一个StackOverflow问题,它有几种不同的执行方法:

http://stackoverflow.com/questions/50744/wait-until-file- is-unlocked-in-net [ ^ ]
The problem is that the FileSystemWatcher tells you immediately when the file was created. It doesn''t wait for the file to be released. The system is still creating the file when you already have the message, which is why you are getting that error message. Basically, you need to wait your turn. Take the event and then have a utility watch that file until it is free for reading. Here is a StackOverflow question that has a few different ways to do this:

http://stackoverflow.com/questions/50744/wait-until-file-is-unlocked-in-net[^]


这篇关于Windows应用程序中的FileSystemWatcher问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆