Files in Watch Directory being locked while using DirectoryInfo

2k views Asked by At

I have been monitoring files in a directory on the network. I had initially used FileWatcher to monitor them. I found that the files were being locked while using FileWatcher so I changed my implementation to use DirectoryInfo to watch for newly arrived and deleted files in the directory that I am watching. It seems while using DirectoryInfo also, the files in the watch directory are getting locked thereby preventing the files from being deleted by another application after downloading the files. My watch application is a windows service.

Could anybody tell me if they have faced issues and if they have, how you have been resolve it ?

Thanks,

2

There are 2 answers

1
jason On

Are you sure that whatever is creating/updating the files is done? If not, the file will be locked.

6
Paaland On

Even though FileWatcher is supposed to work on UNC shares I've had numerous problems doing so. Since your issue is not time-critical I'd create a Thread that just checks if the files are present, Sleeps a few seconds the loops until the files are gone at which time your alert is sent.

NB: Running as a service requires the running user to have network privileges on the remote share as well.

Update: Just did a quick test on our network. Client running Windows 7 server running Windows 2008 R2. Added several files, both small and large to the share. Did not have any problems deleting the files while the code was running. Even without the Thread.Sleep

        bool filesDeleted = false;

        while (!filesDeleted)
        {
            DirectoryInfo di = new DirectoryInfo(@"\\server\share\path\");
            FileInfo[] files = di.GetFiles();

            foreach (var file in files)
            {
                DateTime created = file.CreationTime;
                string fileName = file.Name;

                //Do what every you need to check if the two files are still there
            }

            Thread.Sleep(5000);
        }

        //Send alert