无法在进程中使用命令

问题描述 投票:0回答:1

我正在尝试在 C# 进程中使用“sc.exe”命令,并使用以下代码:

Process p = new Process();
string command = @"sc.exe stop 'MY SERVICE'";
//Create temp files to store output and error from command
var outputTmpFile = Path.GetTempFileName();
var errorTmpFile = Path.GetTempFileName();

ProcessStartInfo info = new ProcessStartInfo()
{
   Verb = asAdmin ? "runas" : "",
   FileName = $"{command}",
   Arguments = $">{outputTmpFile} 2>{errorTmpFile}",
   UseShellExecute = true,
   WindowStyle = runInBackground ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal,
};

p.StartInfo = info;


p.Start();
p.WaitForExit();


但是我在 p.Start() 上一直出现错误,错误:“System.ComponentModel.Win32Exception : '找不到指定文件'

我尝试修改命令以使用cmd或powershell(“cmd /c sc.exe ...”或“powershell sc.exe ...”)。我尝试过不使用 UseShellExecute,但我需要它能够以管理员身份执行一些脚本/exe(sc 也需要管理员)(它们通过提供完整路径来工作)。我还尝试使用 sc 的完整路径,我在 System32 和 SysWOW64 中都找到了它)我的环境变量已设置,因为我可以从终端调用 sc.exe。

我无法让它发挥作用。

感谢您的帮助。

c# .net windows
1个回答
0
投票

您需要设置工作目录:

using System.Diagnostics;

Process p = new Process();
string command = @"sc.exe";
//Create temp files to store output and error from command
var outputTmpFile = Path.GetTempFileName();
var errorTmpFile = Path.GetTempFileName();

ProcessStartInfo info = new ProcessStartInfo()
{
    FileName = $"{command}",
    Arguments = $">{outputTmpFile} 2>{errorTmpFile}",
    UseShellExecute = true,
    WindowStyle = ProcessWindowStyle.Normal,
    WorkingDirectory = @"C:\windows\system32"
};

p.StartInfo = info;

p.Start();
p.WaitForExit();
© www.soinside.com 2019 - 2024. All rights reserved.