8

UPDATE ** STILL LOOKING FOR A CORRECT ANSWER ** I have the following code in my windows service and I want to run a batch file. I want the command prompt window up so I can see progress

here is my code but my batch file code doesnt work

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;

    namespace Watcher
    {
        public partial class Watcher : ServiceBase
        {
            public Watcher()
            {
                InitializeComponent();
            FolderWatcher.Created += FolderWatcher_Created;
            FolderWatcher.Deleted += FolderWatcher_Deleted;
            FolderWatcher.Renamed += FolderWatcher_Renamed;
            }

            protected override void OnStart(string[] args)
            {

                          // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "C:\\myFile.bat";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();


            }

            protected override void OnStop()
            {
            }

            private void FolderWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been created. ");
                writer.Close();
            }

            private void FolderWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been deleted. ");
                writer.Close();
            }

            private void FolderWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\log.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been renamed. ");
                writer.Close();
            }


        }
    }

It does not execute the batch file. I am a newbie in .net and C# and I am not sure what to do from here. thanks

Asim Zaidi
  • 27,016
  • 49
  • 132
  • 221
  • Can you in any way confirm that the service is running? – Babak Naffas Aug 18 '11 at 01:14
  • service is running just fine. I can start it from command line. I can rename / delete / add folders and it logs the info. So I am 100% sure that the service is running just fine – Asim Zaidi Aug 18 '11 at 01:20
  • 3
    Just as a side note: You should wrap your `StreamWriter`s in `using` otherwise you might leave open file handles around. – ChrisWue Aug 18 '11 at 02:04

6 Answers6

4

How to run console application from Windows Service?

You will want to the set the p.StartInfo with FileName="cmd.exe" and Arguments="c:\\thebatfile.bat" i believe

Community
  • 1
  • 1
Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
  • 3
    @Autolycus Yes it does, but you need to change the arguments to `/C "c:\myFile.bat"` (the `/C` was missing). – Justin Aug 23 '11 at 13:41
2

The problem is that you have UseShellExecute as false, but you aren't passing the name of an executable.

When ShellExecute is being used its similar to double clicking on a file in explorer - it knows that .doc files need to be opened with Word, and that .bat files need to be opened with cmd.exe. When you have this disabled however it knows none of these things and you need to pass an executable in order for anything to be run successfully.

As you are setting RedirectStandardOutput to true you need to instead run the batch file via cmd.exe by setting FileName to cmd.exe and the arguments to /C "c:\myFile.bat":

p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C \"c:\\myFile.bat\"";
Justin
  • 84,773
  • 49
  • 224
  • 367
0

Windows services run under a desktopless user account. To see the cmd window you must impersonate the current logged user and start the cmd window on this user's desktop. See this:

Windows Impersonation from C#

Community
  • 1
  • 1
Alexandru Dicu
  • 1,151
  • 1
  • 16
  • 24
0

It looks like it's running the batch script when the service is first run and then it quits (p.WaitForExit();) before the other functions get the ability to be called. Is that the intended behavior? That would explain why you can see it do the folder operations and not see the script being run.

Try this code to bring up the console window. It should give you an idea of when the batch script is running.

protected override void OnStart(string[] args)
{
        // Start the child process.
        Process p = new Process();
        // Redirect the output stream of the child process.
        p.StartInfo.UseShellExecute = false;

        /*
        This is commented out so we can see what the script is doing
        inside the cmd console.
        */
        //p.StartInfo.RedirectStandardOutput = true;

        p.StartInfo.FileName = "C:\\myFile.bat";
        p.Start();
        // Do not wait for the child process to exit before
        // reading to the end of its redirected stream.
        // p.WaitForExit();
        // Read the output stream first and then wait.

        /*
        Since we aren't redirecting the output, we have to comment out
        this line or we get an error
        */
        //string output = p.StandardOutput.ReadToEnd();

        p.WaitForExit();
}
0

i am doubting your service or the bat file. modify the source code to open a notepad! check if notepad shows up!! if yes then we can investigate further!

ioWint
  • 1,609
  • 3
  • 16
  • 34
  • 2
    I dont think you can start notepad in windows service. – Asim Zaidi Aug 18 '11 at 16:09
  • i assumed it should work, didnt know it needs extra work to get the notepad on a windows service. never had a reason to try it earlier! http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/c8c9d2c6-f2bb-4fa4-ba99-51a42f9bc6f4 – ioWint Aug 18 '11 at 16:46
0

What is your batch file doing? Assume you've confirmed that this IS running OK.

glendon
  • 163
  • 1
  • 2
  • 8
  • As a side note - why are you trying to run GUI from a windows service? Seems odd. However, you might find this answer and article of some use: http://stackoverflow.com/questions/677874/starting-a-process-with-credentials-from-a-windows-service – glendon Aug 23 '11 at 13:48