【问题标题】:CMD doesn't work when starting as a .NET process作为 .NET 进程启动时,CMD 不起作用
【发布时间】:2015-03-22 15:47:30
【问题描述】:

尝试使用以下 F# 代码捕获 Windows 命令提示符输出:

let cmd = new Process()
cmd.StartInfo.FileName <- "cmd.exe"
cmd.StartInfo.UseShellExecute <- false 
cmd.StartInfo.CreateNoWindow <- true
cmd.StartInfo.RedirectStandardInput <- true
cmd.StartInfo.RedirectStandardOutput <- true
cmd.StartInfo.RedirectStandardError <- true
cmd.Start() |> ignore

let input = cmd.StandardInput
let output = cmd.StandardOutput
let err = cmd.StandardError
input.AutoFlush <- true
input.Write("dir" + Environment.NewLine)
input.Write("exit" + Environment.NewLine)

cmd.WaitForExit()
if not cmd.HasExited then cmd.Kill()

input.Flush()
let result = output.ReadToEnd()
let error = err.ReadToEnd()
printfn "RESULT\n%s\nERROR\n%s" result error
input.Close()
output.Close()
err.Close()

cmd.Dispose()

结果...

RESULT
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\{username}\AppData\Local\Temp>dir

C:\Users\{username}\AppData\Local\Temp>exit

ERROR
'dir' is not recognized as an internal or external command,
operable program or batch file.

事实上,所有其他命令的结果都是相同的 ('{command}' is not recognized...),例如 cd.. 等,否则从手动启动和键入的命令提示符下可以正常工作。

我做错了什么?

【问题讨论】:

  • 在 Visual Studios 2013 中运行上述代码对我来说效果很好。我无法重现您的错误。

标签: .net process cmd f# command-prompt


【解决方案1】:

虽然仍然不清楚为什么,使用.StartInfo.Arguments 有效,但使用.StandardInput 执行命令不起作用,例如

cmd.StartInfo.Arguments <- "/C dir" 

解决了这个难题。

【讨论】:

    【解决方案2】:

    请看看我的 Cronix 项目。 也许你会在那里找到答案

    https://github.com/aph5nt/cronix/blob/master/tests/Cronix.Tests/ServiceEnviroment.fs

    【讨论】:

      猜你喜欢
      • 2012-10-07
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多