Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

windows - Get the output of a shell Command in VB.net

I have a VB.net program in which I call the Shell function. I would like to get the text output that is produced from this code in a file. However, this is not the return value of the executed code so I don't really know how to.

This program is a service but has access to the disk no problem as I already log other information. The whole service has multiple threads so I must also make sure that when the file is written it's not already accessed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You won't be able to capture the output from Shell.

You will need to change this to a process and you will need to capture the the Standard Output (and possibly Error) streams from the process.

Here is an example:

        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)

To get the standard error:

'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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...