【问题标题】:Get the output of a shell Command in VB.net在 VB.net 中获取 shell 命令的输出
【发布时间】:2012-02-07 05:08:17
【问题描述】:

我有一个调用 Shell 函数的 VB.net 程序。我想在文件中获取从此代码生成的文本输出。但是,这不是执行代码的返回值,所以我真的不知道该怎么做。

该程序是一项服务,但可以访问磁盘没有问题,因为我已经记录了其他信息。整个服务有多个线程,所以我还必须确保在写入文件时它还没有被访问过。

【问题讨论】:

    标签: vb.net windows shell


    【解决方案1】:

    您将无法捕获 Shell 的输出。

    您需要将其更改为进程,并且需要从该进程中捕获Standard Output(可能还有错误)流。

    这是一个例子:

            Dim oProcess As New Process()
            Dim oStartInfo As New ProcessStartInfo("ApplicationName.exe", "arguments")
            oStartInfo.UseShellExecute = False
            oStartInfo.RedirectStandardOutput = True
            oProcess.StartInfo = oStartInfo
            oProcess.Start()
    
            Dim sOutput As String
            Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
                sOutput = oStreamReader.ReadToEnd()
            End Using
            Console.WriteLine(sOutput)
    

    获取标准错误:

    'Add this next to standard output redirect
     oStartInfo.RedirectStandardError = True
    
    'Add this below
    Using oStreamReader As System.IO.StreamReader = checkOut.StandardError
            sOutput = oStreamReader.ReadToEnd()
    End Using
    

    【讨论】:

    • @DT,您评论中提供的链接不再有效 - 您是否知道此行为的任何其他确认?
    【解决方案2】:

    只需将输出通过管道传输到文本文件?

    MyCommand > "c:\file.txt"
    

    然后读取文件。

    【讨论】:

    • 其实,我昨晚在阅读本文之前确实找到了解决方案,并且非常接近。我将使用 >> 代替,因为我想每次都附加结果,但还是谢谢你。
    • 我忘了提到如果你还想在文件中捕获错误报告,你应该考虑MyCommand > "c:\file.txt 2>&1。默认情况下,错误输出不包含在文件中。
    • @mark :我不是反对者,但我可以解释:我讨厌不得不使用“保存到文件”“读取文件”。它很慢,很糟糕,很丑
    【解决方案3】:
        Dim proc As New Process
    
        proc.StartInfo.FileName = "C:\ipconfig.bat"   
        proc.StartInfo.UseShellExecute = False
        proc.StartInfo.RedirectStandardOutput = True
        proc.Start()
        proc.WaitForExit()
    
        Dim output() As String = proc.StandardOutput.ReadToEnd.Split(CChar(vbLf))
        For Each ln As String In output
            RichTextBox1.AppendText(ln & vbNewLine)
            lstScan.Items.Add(ln & vbNewLine)
        Next
    

    ================================================ ========================= 分两行创建一个批处理文件,如下所示:

        echo off
        ipconfig
    

    ' 确保将此批处理文件保存为 ipconfig.bat 或您决定选择的任何名称,但请确保您将点 bat 放在它的末尾。

    【讨论】:

    • 您的部分代码片段已滑出代码框
    • 在现有命令之后命名批处理文件将导致无限循环。我很难做到:-)
    猜你喜欢
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2018-02-11
    • 2013-08-21
    • 1970-01-01
    相关资源
    最近更新 更多