C# 当命令等待用户输入时,Process.Start()挂起服务

C# 当命令等待用户输入时,Process.Start()挂起服务,c#,C#,我有一个应用程序,用户可以输入dos命令,稍后由服务运行。以下是用户可以输入内容的示例: 这很好,但由于服务运行该命令,因此/Q参数必须存在,因为没有人机交互。我试图弄清楚当/Q丢失时,该服务如何优雅地处理。现在,服务实际上挂起,必须停止(几次),然后重新启动。这是因为没有/Q的命令最终等待用户输入 这是运行命令的(精简)代码: using (Process process = new Process()) { string processOutput = string.Empty;

我有一个应用程序,用户可以输入dos命令,稍后由服务运行。以下是用户可以输入内容的示例:

这很好,但由于服务运行该命令,因此
/Q
参数必须存在,因为没有人机交互。我试图弄清楚当
/Q
丢失时,该服务如何优雅地处理。现在,服务实际上挂起,必须停止(几次),然后重新启动。这是因为没有
/Q
的命令最终等待用户输入

这是运行命令的(精简)代码:

using (Process process = new Process())
{
    string processOutput = string.Empty;

    try
    {
        process.StartInfo.FileName               = "file name (cmd in this case)";
        process.StartInfo.Arguments              = "parameters (with the \Q)";
        process.StartInfo.UseShellExecute        = false;
        process.StartInfo.RedirectStandardError  = true;
        process.StartInfo.RedirectStandardInput  = true;
        process.StartInfo.RedirectStandardOutput = true;

        process.Start();

        processOutput = process.StandardOutput.ReadToEnd();

        process.WaitForExit();
    }
    catch (Exception ex)
    {
        Logger.LogException(ex);
    }
挡块没有被击中。该服务将一直挂起,直到我手动停止并启动它


有没有可能处理这种情况,使服务不会挂起?我甚至不知道该尝试什么。

一种方法是在未找到的情况下添加
/Q

process.StartInfo.Arguments = arguments.AddQuietSwitch();
扩展方法:

private static Dictionary<string, string> _quietSwitchMap =
    new Dictionary<string, string> { { "rmdir", "/Q" }, { "xcopy", "/y" } };

public static string AddQuietSwitch(this string input)
{
    var trimmedInput = input.Trim();
    var cmd = trimmedInput.Substring(0, trimmedInput.IndexOf(" "));

    string switch;
    if (!_quietSwitchMap.TryGetValue(cmd, out switch)) { return input; }
    if (trimmedInput.IndexOf(switch, 0,
        StringComparison.InvariantCultureIgnoreCase) > 0 { return input; }

    return input += string.Format(" {0}", _quietSwitchMap[cmd]);
}
private static Dictionary\u quietSwitchMap=
新字典{{“rmdir”,“/Q”},{“xcopy”,“/y”};
公共静态字符串AddQuietSwitch(此字符串输入)
{
var trimmedInput=input.Trim();
var cmd=trimmedInput.Substring(0,trimmedInput.IndexOf(“”);
串开关;
如果(!_quietswitcmap.TryGetValue(cmd,out开关)){return input;}
如果(trimmedInput.IndexOf)(开关,0,
StringComparison.InvariantCultureIgnoreCase)>0{返回输入;}
返回input+=string.Format(“{0}”,_quietswitcmap[cmd]);
}
您可以附加

回音y | rmdir


例如,
/Q
是特定于
rmdir
xcopy
而不是
/y
的。另外,请在不敏感的情况下搜索case,以查找
/Q
/Q
。实际上,这不起作用,因为用户可以输入任何DOS命令,而且大多数都可以我不需要安静模式。啊,很好。所以基本上只需要寻找rmdir或xcopy(可能还有其他需要安静模式的东西),然后添加/Q(或/y)如果它丢失了。实际上,最好在UI中检测到这一点,并且在没有quiet命令的情况下不允许使用rmdir或xcopy。+1因为这是一个很好的解决方法。我仍然想知道是否有办法捕捉到这一点,因为可能还有另一个命令(我没有想到)这可能需要安静模式。我也不想让服务挂起。如果没有人能想出一个方法来捕捉这个,我会接受你的答案。谢谢!啊,我明白了。提示会出现,回音Y会对提示回答“是”。+1是有趣的提示,但它仍然不包括rmdir或xcopy以外的其他内容已使用。注意:
echo Y
可能会回答安静模式以外的问题。例如,我尝试了一个xcopy,出现了以下提示:
C:\temp\AnotherTemp\snuh.txt是否在目标上指定了文件名或目录名(F=file,D=directory)?
echo y
导致
y
成为预期为F或D的问题的答案。