views:

60

answers:

2

I'm writing a Windows Service that needs to take a file from an FTP folder on the local computer and parse the data in that file, and push it to an external source. The file will be uploaded to the FTP folder at some point from some other party, and I can't predict when the file will be uploaded. I need the service to be able to scan the FTP folder and recognize when the file has been recently uploaded to the server, and kick off the parsing process.

I need some know if there's some way in .NET to be able to detect when a file was put into a directory.

There is a similar question in SO about this here, but it wasn't in regards to writing a windows service. Also, the solution seemed to be to monitor the directory itself, but I tested that idea using the DirectoryInfo class and it doesn't work when looking at the LastWriteTime property. The time of the directory doesn't change when I copy and replace a file in the directory.

Note: I can't rely on the create/modify timestamps on the file, being as I don't know how the other party is generating these files.

+3  A: 

Use a FileSystemWatcher. That will throw a "Changed" (Or even a "created" I believe) event which you can handle. You'll need to be careful to make sure the file is fully written before you start working with it, but that should get you pointed in the right direction.

EDIT: To Joseph's question about how, here's a static method I keep in my utilities class for just such occasions:

public static bool FileComplete(string filePath)
        {
            try
            {
                File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                return true;
            }
            catch { return false; }
        }

Then I just a While(!FileComplete(foo)) {} before my actual file handling.

AllenG
Thanks AllenG, but how would I go about figuring out if the file is fully written? Would I gather that from the FileInfo class?
Joseph
The way I do it is to attempt to open the file with FileSharing.None to see if ftp transaction is still attempting to write to the file. Once you're able to open it that way, you should be good to go.There may be a better way, but if so, I don't know it.
AllenG
A: 

Take a look at FileSystemWatcher.

Sani Huttunen