2015-11-02 144 views
1

我要运行用C#CMD命令在Windows中安装的服务,我使用的代码如下:cmd命令不执行在C#

class Program 
{ 
    static void Main(string[] args) 
    { 
     System.Diagnostics.Process process = new System.Diagnostics.Process(); 
     System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 
     startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
     startInfo.CreateNoWindow = false; 
     startInfo.FileName = "cmd.exe"; 
     startInfo.Arguments = 
      "\"C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\installutil.exe\" \"D:\\Projects\\MyNewService\\bin\\Release\\MyNewService.exe\""; 
     process.StartInfo = startInfo; 
     process.Start(); 

    } 
} 

但这个方案不工作。如果我在cmd.exe中运行这个命令可以正常工作,但是当我运行这个项目时不要执行命令并且MyNewService.exe不要安装。

我的问题在哪里? 你帮我吗?

+4

您是否运行cmd runas管理员? –

+1

是的,我的项目以管理员身份运行。在此之前,我添加了startInfo.Verb =“runas”;但不工作。 –

回答

3

不是启动cmd.exe并将installutil作为参数传递(然后将服务executabel作为参数的参数),请尝试直接传递MyNewService.exe作为参数来启动installutil.exe可执行文件。

您应该始终等待进程退出,并且应该始终检查进程的退出代码,如下所示。

static void Main(string[] args) 
{ 

    System.Diagnostics.Process process = new System.Diagnostics.Process(); 
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
    startInfo.CreateNoWindow = true; 
    startInfo.FileName = "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\installutil.exe"; 
    startInfo.Arguments = "D:\\Projects\\MyNewService\\bin\\Release\\MyNewService.exe"; 
    process.StartInfo = startInfo; 
    bool processStarted = process.Start(); 
    process.WaitForExit(); 
    int resultCode = process.ExitCode; 
    if (resultCode != 0) 
    { 
     Console.WriteLine("The process intallutil.exe exited with code {0}", resultCode); 
    } 
} 
+1

谢谢,它的工作。 –