Search code examples
c#.netsortingservicefilesystemwatcher

FileSystemWatcher sort algorithm


I've created a simple FileSystemWatcher service that's running on my PC:

    public static void Run()
    {

        var watcher = new FileSystemWatcher
        {
            Path = @"C:\Users\XXX\Google Drive",
            NotifyFilter = NotifyFilters.LastAccess
                           | NotifyFilters.LastWrite
                           | NotifyFilters.FileName
                           | NotifyFilters.DirectoryName,

            Filter = "*.*",
        };

        watcher.Created += OnChanged;
        watcher.EnableRaisingEvents = true;
    }

    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        FooPrintClass.SendToPrinter(e.FullPath);
    }

As you see I'm watching a Google Drive folder. That folder is also synced on my server. From time to time a system on my server will create 2 pair of files with the same name but with diffrent type:

(Foo.pdf, Foo.txt)

Sometimes the system will create over 50 of those pairs and they all will be synced to my Google Drive folder.

So far so good, now to my problem: My FileSystemWatcher service do work as expected, but it dosen't treat them in any sorting matter at all. I need my service to actually process each pair at a time.

Expected Result:
Foo.pdf, Foo.txt
Bar.pdf, Foo.txt

Actual Result: 
Bar.txt, Foo.pdf
Foo.txt, Bar.pdf

As the expected result show, I need to print the pairs in order first. There are many ways to implement a "queue" solution, but in my case I don't know how many files there will be. So I don't know the total of the files and therefor it'll be harder to build a queue and sorting algorithm.

Any tips?


Solution

  • As you use 3d party system for syncing files you have no control how it is done. You may have problems - no control in which order or they are synced, no guaranty that when you get a notification from your watched a file is not locked.

    To easy the problem with sync order you may sync files in bundles. If you could modify the system that creates these files, you can ZIP both files in one zip file. Having Foo.zip you can print both files in order you want.

    It doesn't solve the problem with possible locking. If you could notify your service somehow about a new pair of files, you can just download these files directly from Google Drive using the API. In this case you will have full control over files and the order you get them.