Search code examples
c#topshelf

Re-create folder after re-start of window service using Topshelf


I am using Topshelf for window service and I used configuration AfterInstall to create a folder CreateFolder.

Now when I install/start service, the folder gets created. Nice!

lets say after some time I stopped my service and delete the folder which creates, then upon re-start of service, I want to folder to be re-created. Is this possible?

Is there any setting within Topshelf configuration so that on re-start of service folder will create again?

HostFactory.Run(
        configuration =>
        {
            configuration.AfterInstall(CreateFolder);
            configuration.Service<Service1>(
                service =>
                {
                    service.ConstructUsing(x => new Service1());
                    service.WhenStarted(x => x.Start());
                    service.WhenStopped(x => x.Stop());
                });
            configuration.EnableServiceRecovery(recoveryOption =>
            {
                recoveryOption.RestartService(1);
            });

            configuration.RunAsVirtualServiceAccount();

            configuration.SetServiceName("TEST");

            configuration.StartAutomatically();

"CreateFolder" Method below here,

static void CreateFolder()
    {
            Directory.CreateDirectory(some path);
    }

Solution

  • TopShelf only has custom actions for the AfterInstall. You could tie into the service Start() function to check for and create the directory using the Directory.CreateDirectory(path) method.