Run Custom Command in C# Windows Service
I have a custom console command, which if executed in command prompt just displays some text in the command window (similar to 'dir' command).
I'm trying to execute the command 'myCommand' from a windows service and it is always returning blank string values. However, if run the same command in a command prompt, the result is displ开发者_运维问答ayed in the command window. Also, if I run the below code in a windows forms application, it works fine and I get the same data which is displayed in the command screen to a string variable.
Where am I going wrong? Why is the code returning a blank string when I execute it from a windows service, where as it works in a forms application. Is there any other method to capture the result of a command to a string variable in a windows service? Please advise. Thank you.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c myCommand");
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Attach the Visual Studio debugger to your running service (Debug menu, Attach to Process), put a breakpoint in the code where you execute the the command, and then execute the comand. This will enable you to debug the problem. If necessary, you can call the System.Diagnostics.Debugger.Break method in your service to force it to break into the debugger at the appropriate point, without having to attach the debugger first.
Edit:
I suggest you also capture the standard error stream:
procStartInfo.RedirectStandardError = true;
...
string error = proc.StandardError.ReadToEnd();
proc.WaitForExit();
Check what you get in the error string. I use WaitForExit to wait until the command exits too.
You are not setting the working Directory (ie procStartInfo.WorkingDirectory), so if the system can not find 'myCommand' , you will get this result.
Even if 'myCommand' is in the same directory as your service exe file, that does not normally work as the working directory for a service is normally windows\system32.
I preferred this Easier way to debug a C# Windows Service
I added the conditional If to launch the debugger from the OnStart method, then put a breakpoint in my OnCustomCommand(int command) method.
精彩评论