How might I schedule a C# Windows Service to perform a task daily?

I wouldn’t use Thread.Sleep(). Either use a scheduled task (as others have mentioned), or set up a timer inside your service, which fires periodically (every 10 minutes for example) and check if the date changed since the last run: private Timer _timer; private DateTime _lastRun = DateTime.Now.AddDays(-1); protected override void OnStart(string[] args) { _timer = … Read more

Detecting USB drive insertion and removal using windows service and c#

You can use WMI, it is easy and it works a lot better than WndProc solution with services. Here is a simple example: using System.Management; ManagementEventWatcher watcher = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery(“SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2”); watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Query = query; watcher.Start(); watcher.WaitForNextEvent();

Create Windows service from executable

To create a Windows Service from an executable, you can use sc.exe: sc.exe create <new_service_name> binPath= “<path_to_the_service_executable>” You must have quotation marks around the actual exe path, and a space after the binPath=. More information on the sc command can be found in Microsoft KB251192. Note that it will not work for just any executable: … Read more

Easier way to debug a Windows service

If I want to quickly debug the service, I just drop in a Debugger.Break() in there. When that line is reached, it will drop me back to VS. Don’t forget to remove that line when you are done. UPDATE: As an alternative to #if DEBUG pragmas, you can also use Conditional(“DEBUG_SERVICE”) attribute. [Conditional(“DEBUG_SERVICE”)] private static … Read more

Best Timer for using in a Windows service

Both System.Timers.Timer and System.Threading.Timer will work for services. The timers you want to avoid are System.Web.UI.Timer and System.Windows.Forms.Timer, which are respectively for ASP applications and WinForms. Using those will cause the service to load an additional assembly which is not really needed for the type of application you are building. Use System.Timers.Timer like the following … Read more

Map a network drive to be used by a service

Use this at your own risk. (I have tested it on XP and Server 2008 x64 R2) For this hack you will need SysinternalsSuite by Mark Russinovich: Step one: Open an elevated cmd.exe prompt (Run as administrator) Step two: Elevate again to root using PSExec.exe: Navigate to the folder containing SysinternalsSuite and execute the following … Read more