1

I want to use nssm (Non-Sucking Service Manager) application to be able to install bat files as windows services and then control them. (start, stop, get status etc.). Note that I placed nssm.exe into C drive.

I tested my code and it works for a simple command like "ping localhost". But if I run nssm commands then it works weird. For example if I run:

C:\nssm.exe status WindowsServiceName

Then it gives me that output:

S\0E\0R\0V\0I\0C\0E\0_\0S\0T\0O\0P\0P\0E\0D\0\r\0\n\0

Actually the output is correct. It writes "SERVICE_STOPPED" but there are lots of weird characters and when I open it in Text Visualizer it shows just "S".

If I run this command:

C:\nssm.exe start WindowsServiceName

It gives empty output and service does not start. But if I manually open a command prompt and run these codes, everything works fine.

Here is my code:

using System.Diagnostics;

namespace NssmTestApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string cmdCommand = @"C:\nssm.exe start WindowsServiceName";
            string output = RunCmdCommand(cmdCommand);
        }

        private static string RunCmdCommand(string cmdCommand)
        {
            string output = "";

            ProcessStartInfo startInfo = new ProcessStartInfo();

            startInfo.WindowStyle = ProcessWindowStyle.Hidden;

            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "/C " + cmdCommand;
            startInfo.Verb = "runas";

            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardError = true;

            Process process = Process.Start(startInfo);

            while (!process.HasExited)
            {
                output += process.StandardOutput.ReadToEnd();
            }

            return output;
        }
    }
}

How can I make this code work or is there a more efficient way for installing bat files as windows service and then starting, stopping them, getting their status etc.?

Orkun Bekar
  • 1,447
  • 1
  • 15
  • 36
  • Looks like NSSM is generating UTF-16 output. – Harry Johnston Jul 28 '16 at 04:10
  • Setting StandardOutputEncoding property of startInfo to Encoding.Unicode solved that problem. So you are right. Write an appropriate answer for this situation please so I will mark it as answer. – Orkun Bekar Jul 28 '16 at 07:26
  • A self-answer would be more appropriate in this case. I pointed out the problem, but you figured out the solution. If possible, please post the corrected code. – Harry Johnston Jul 28 '16 at 08:50

0 Answers0