Forum Moderators: open

Message Too Old, No Replies

Automatically checking a folder for new files

How to model the application?

         

bhonda

2:38 pm on Jan 13, 2010 (gmt 0)

10+ Year Member



Hey guys,

I've got a theory question for you all.

My aim is to fire a c# method when a new file is added to a specific folder on the server (Windows Server). This code can be within a website, windows application or a webservice, etc, that is not my issue (not yet, anyway!).

What I'm struggling with is how do I model the application. From what I can see, I have two options -

1. Create an application that is constantly running, that keeps on checking the folder every so often, then calling the code when a new file is found.

2. Somehow create a trigger on the folder that somehow calls a method somewhere.

As you may notice, I don't really understand how I would do point 2!

So, my question - how has this been done before, and what have you learnt from doing this?

All suggestions would be greatly appreciated!

Thanks,

B

Ocean10000

3:07 pm on Jan 13, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I mostly do web applications, so I have done this in that context only. I use the FileSystemWatcher class to monitor for changes, and wait for those events. The web server is always running so it makes it easier for me at least. I have added the link to the standard class which does all the magic for me.

Reference:
MSDN FileSystemWatcher [msdn.microsoft.com]

bhonda

3:41 pm on Jan 13, 2010 (gmt 0)

10+ Year Member



That looks perfect - in terms of checking what's changed, that will do exactly what I'm looking for - thanks!

bhonda

11:16 am on Jan 14, 2010 (gmt 0)

10+ Year Member



Hey,

Just a little follow-up - some of the files I'm waiting on can be quite large, and I'm finding it hard to work out when a file has been completely copied.

For example, when a new file is added, I get a CREATED event fired, and then two or three CHANGED events, a few seconds after the initial event (depending on the file size).

Have you (or anyone) figured out a good methodology for working out when a file has finished being copied into a folder?

Cheers,

B

marcel

11:36 am on Jan 14, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've no experience with using the FileSystemWatcher on very large files. But you could try opening the file in exclusive mode when the event is fired, if opening succeeds continue, otherwise wait for the next event, ie.

FileStream fs = null;
try
{
// Attempt opening file
fs = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.None);
}
catch
{
// Open file failed, probably still being written to
return;
}
finally
{
if (fs != null)
{
fs.Close();
}
}
// Otherwise, continue with normal operation

* Edit - Cleaned up code