Click here to Skip to main content
15,908,455 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have developed a filesystemWatcher console application, when I am running it its catching the file changes but when I have to deploy this as a schedule task, I am unable to make it catch the file changes because watcher runs for a second maybe if the file is already there it won't catch the changes.

Can anybody please help me in achieving this task I want to make this FileSystemWatcher class to pickup the created or modified files and put its path and details in a Table.

Here is my code:
public class Watcher
    {
        public static void Main(string[] args)
        {
            Run(args);
        }

        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static void Run(string[] args)
        {
            // If a directory is not specified, exit program.
            if (args.Length < 1)
            {
                // Display the proper way to call the program.
                Console.WriteLine("Usage: Watcher.exe (directory)");
                return;
            }

            // Create a new FileSystemWatcher and set its properties.
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = args[0];
            /* Watch for changes in LastAccess and LastWrite times, and
               the renaming of files or directories. */
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.Size;// | NotifyFilters.DirectoryName;
            // Only watch text files.
            watcher.Filter = "*.*";

            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnCreated);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);

            // Begin watching.
            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
        }

        //Fires if file changed.
        private static void OnChanged(object source, FileSystemEventArgs e)
        {
            if (ExecutePackage(e.FullPath))
                File.Delete(e.FullPath);
        }

        //Fires if file Created.
        private static void OnCreated(object source, FileSystemEventArgs e)
        {            
            if (ExecutePackage(e.FullPath))
                File.Delete(e.FullPath);
        }

        //Fires if file Renamed.
        private static void OnRenamed(object source, RenamedEventArgs e)
        {
            if (ExecutePackage(e.FullPath))
                File.Delete(e.FullPath);
        }

        /// 
        /// This is the root directory where the flat files are going to be loaded
        /// 
        private static bool ExecutePackage(string fileFullPath)
        {
            string errorDescription = string.Empty;
            DTSPackage _package = new DTSPackage();

            try
            {
                if (!File.Exists(fileFullPath))
                    return false;

                string strFileExt = (Path.GetExtension(fileFullPath) ?? string.Empty).ToLower();
                string directoryFullPath = Path.GetDirectoryName(fileFullPath) + @"\";
                string sourceFileName = Path.GetFileNameWithoutExtension(fileFullPath);

                if (Regex.IsMatch(strFileExt, @"\.txt|\.csv", RegexOptions.IgnoreCase))
                {
                    int result = WatcherDB.CallGetImportMetaData(fileFullPath);

                    if (result >= 1)
                        return true; 
                }
            }            
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace, "Exception Details");
            }
            finally
            {
                _package.ClearPackage();
            }
            MessageBox.Show(errorDescription);
            return false;
        }
    }


What I have tried:

I am searching in google and asking with friends etc.
Posted
Updated 3-Oct-16 0:16am

1 solution

Why are you scheduling a task? If you simply let the app run all the time, it will detect file system changes whenever they happen. Consider writing a Windows service instead. Those get loaded/executed when the system starts up, and can run without a user being logged on.
 
Share this answer
 
v2
Comments
[no name] 3-Oct-16 13:19pm    
The reason is there are bunch of Applications like that, and we need to pass Command-line arguments to them. Is there anyway to do the same using Schedule Tasks, even though its Windows Service, it has to start and stop, then I don't know how FileSystemWatcher picks up when the file was created sometime before?
FileSystemWatcher is catching only files that are created or changed when its running, how can I catch the files that are already existing in the folder.
#realJSOP 3-Oct-16 14:41pm    
If you insist on doing it that way, You're going to have to scan the folder manually either before or after firing up the FileSystemWatcher.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900