1

I have a Windows Service that I successfully deploys, successfully works when debugging, but crashes when a file is added to the monitored directory.

I thought it was an issue with my impersonator being used between the OnStart and InputOnChanged, but the crash still happens when I run the service under my own domain user.

I have EventLog set to write to it's own application source, but none of my WriteEntrys are called except the one in the OnStart function. I've been trying different tweaks and feel like I need another set of eyes to see something i'm not:

protected override void OnStart(string[] args)
        {
            //using(Impersonator context = new Impersonator("XXXXX", "XXXXXXXX", "XXXXXXXXXX"))
            //{
            try
            {
                this.fileWatcherService = new FileSystemWatcher(baseFilePath, "*.txt")
                {
                    NotifyFilter = NotifyFilters.LastWrite
                };
                fileWatcherService.Changed += InputOnChanged;
                fileWatcherService.EnableRaisingEvents = true;
                eventLog.WriteEntry("XXXX-XXXXX-Service Started");
            }
            catch (Exception ex)
            {
                eventLog.WriteEntry($"{baseFilePath} was not accessible to monitor because {ex.Message}", EventLogEntryType.Error);
            }
        }
protected void InputOnChanged(object source, FileSystemEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Changed)
            {
                eventLog.WriteEntry($"Change Detected - File {e.Name}", EventLogEntryType.Information);
                try
                {
                    fileWatcherService.EnableRaisingEvents = false;
                    eventLog.WriteEntry("Starting process for file: " + e.Name);
                    if (!File.Exists(e.FullPath))
                    {
                        eventLog.WriteEntry($"{e.Name} was not accessible", EventLogEntryType.Error);
                    }

                    //Copy File to backup copy before formatting
                    File.Copy(e.FullPath
                        , Path.Combine(@"\\XXXXXX\XXXXXX\XXXXXXXX\XXXXXXXXXX XXX XXXXXXXXX\XXX\XXXX\XXXX\BackupFiles", GetBackupFileName(e.Name))
                        , false);

                    //Save formatted file to directory
                    List<string> lines = System.IO.File.ReadAllLines(e.FullPath).ToList();
                    File.WriteAllText(Path.Combine(@"\\XXXXXX\XXXXXX\XXXXXXXX\XXXXXXXXXX XXX XXXXXXXXX\XXX\XXXX\XXXX\FormattedFiles", GetFormattedFileName(e.Name))
                        , CSVFormatService.FormatLines(lines));

                    //Remove file from base path to prevent re-processing
                    File.Delete(e.FullPath);
                    eventLog.WriteEntry($"Successfully moved {e.FullPath}", EventLogEntryType.Information);

                }
                catch (Exception ex)
                {
                    eventLog.WriteEntry("XXXX-XXXXX-Service exception: " + ex.Message, EventLogEntryType.Error);
                }
                finally
                {
                    fileWatcherService.EnableRaisingEvents = true;
                }
            }
        }

Would expect eventLog.WriteEntry("Starting process for file: " + e.Name); to update the Application log at least because that is before any attempt to touch a file, but I don't see that in the log. However, the service runs until I place a test file in the monitored directory, and then crashes with a unhandled exception of file does not exist

Jacob Boyd
  • 672
  • 3
  • 19
  • Is this a remote UNC path that is being monitored? Also, are you able to run it with all code except for logging removed, does the event fire, if so, can you try adding code back line by line until the FileNotFound exception. I would also write e.FullPath and the derived file names to the log to make sure they are what you think they should be. – Ross Bush Aug 11 '22 at 21:09
  • Does the exception show up in the event logs? If so, what does the stack look like. Failing that, do you have somewhere to log it – Flydog57 Aug 11 '22 at 21:14
  • Also, check out this article. It looks similiar -> https://stackoverflow.com/questions/11219373/filesystemwatcher-to-watch-unc-path – Ross Bush Aug 11 '22 at 21:18
  • @RossBush that is a UNC path. I haven't tried running it without the logging, but will try it now. Also thank you for sharing that link, it has given me two other paths to try. The UNC path doesn't give an issue when debugging the process out of Visual Studio, only when setting it as a service regardless of the user assigned to the service. – Jacob Boyd Aug 12 '22 at 13:39

1 Answers1

1

When building out these services, make sure you reference a shared project correctly. This issue was caused by adding a reference to a class library to the project, but the .dll was missing when deploying the service. So when the service tried to access the .dll to process data a FileNotFound exception was being thrown. This also make sense as to why the exception was marked as unhandled.

Jacob Boyd
  • 672
  • 3
  • 19