Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
1.33/5 (3 votes)
See more:
Hello,

I want to trigger windows service start if there is a new XML file added to the folder(using filesystemwatcher)

1. Monitor folder - if new xml file is added
2. start service - perform action in the service.
3. stop service
4. create log
5 and move the xml file to archive.

Please help me with a sample code.

Thanks,
Deepthi.

What I have tried:

I tried this
How to implement a simple filewatcher Windows service in C#[^]
Posted
Updated 28-Feb-18 0:00am
Comments
Richard Deeming 27-Feb-18 14:15pm    
So you want a service running all the time, monitoring the directory, which starts and stops a second service when a file is created?!

Just have a single service. When a file is created, either execute the code to process the file, or launch an external console application to process it.
#realJSOP 27-Feb-18 14:34pm    
Like Richard said, just use one service, but I put it to you that using a FileSystemWatcher might be overkill if you're just watching one folder. You could easily put it in a thread and simply check for new files every so often (1 minute or so, depending on how immediate the response needs to be).
Member 13699897 27-Feb-18 15:18pm    
Thanks for the suggestions Richard and John. Yes I want to create single service that can monitor a folder and trigger service start and stop whenever a new XML file is added to that folder.
Please help me with a sample code.
ZurdoDev 27-Feb-18 16:41pm    
There is sample code all over the place. This particular forum is for asking specific questions on code you are stuck on.
Member 13699897 27-Feb-18 17:00pm    
I could find sample code to create windows services and I created one for filesystemwatcher.
I also created another service that executes code whenever I start and stop the service. I am stuck at combining these services. I want to know if there is a better way to create one service(to create single service that can monitor a folder and trigger service start and stop whenever a new XML file is added to that folder)
Thanks.

1 solution

Your design is inefficient and needlessly increases project complexity.

I would do it with ONE multi-threaded service that does NOT use FileSystemWatcher.

The main thread would monitor the folder in question for new files (I would use React/Rx library for this).

When a new file is detected, it would start another thread (or an async task) to perform whatever action needed to be performed on the file.

The reason for using threads is because you never know how long it will take to process the file, and you don't want to delay processing on subsequent files.

Providing appropriate "sample code" for this would really exceed what Q/A is intended for. What you should do is actually make at least one attempt to write the code yourself, and come here when you have questions.
 
Share this answer
 
Comments
Member 13699897 28-Feb-18 15:00pm    
My Code-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace PublicationService
{
partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}

public void Debug()
{
KillProcess();
}

protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
Log("Monitoring Started");
fileSystemWatcher1.EnableRaisingEvents = true;
fileSystemWatcher1.Path = ConfigurationManager.AppSettings["WatchPath"];
fileSystemWatcher1.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
fileSystemWatcher1.Changed += new FileSystemEventHandler(fileSystemWatcher1_Created);
}

protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
fileSystemWatcher1.EnableRaisingEvents = false;
fileSystemWatcher1.Dispose();
Log("Monitoring Stopped");
}

private void KillProcess()
{
TimeSpan timeout = TimeSpan.FromMilliseconds(0);
try
{
string processName = "explorer"; //"InDesignServer.exe";
Process[] processes = Process.GetProcessesByName(processName);
foreach (var process in processes)
{
if (process.ProcessName.Contains(processName))
{
process.Kill();
process.WaitForExit(Convert.ToInt32(timeout));
Log("killed Process");
}
}
}
catch (Exception)
{
// ignored
}
}
private void Log(string message)
{
try
{
string logmessage = $"{message} {Environment.NewLine}";
string logpath = ConfigurationManager.AppSettings["LogPath"];
using ((File.Exists(logpath)) ? File.AppendText(logpath) : File.CreateText(logpath))
{
File.AppendAllText(ConfigurationManager.AppSettings["LogPath"], logmessage);
}

}
catch (Exception)
{
// ignored
}
}

private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{
Log(string.Format("File Changed :Path:{0}, Name{0}", e.FullPath, e.Name));
KillProcess();
}
}
}
i could install the service but when I start, it automatically stops. Dont know why.
#realJSOP 28-Feb-18 15:55pm    
Put your code in your question. Your service stops right away because it got to the end of the OnStart method, and there is no thread keeping it alive. Now do you understand why I said not to use a 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