我有一个应用程序,用户可以在其中输入一个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]);
}

08-06 02:13