Visual Basic,从cmd捕获输出

时间:2018-10-07 18:45:39

标签: vb.net cmd capture-output

对不起,如果之前有人问我,我发现其他解决方案对我来说太复杂了。 无论如何,我试图在视觉基本代码中通过cmd搜索图像,并将图像路径保存为字符串,但是我似乎无法正确捕获cmd的输出。 任何帮助将不胜感激,谢谢!。

代码:

    Dim imageLocation As String
    Dim cmd As New Process
    Dim SR As System.IO.StreamReader
    cmd.StartInfo.FileName = "cmd.exe"
    cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
    cmd.StartInfo.Arguments = "/C dir /b/s Roey.png"
    cmd.Start()
    SR = cmd.StandardOutput
    imageLocation = SR.ReadLine

已更新,所以我发现将输出保存到txt文件,然后读取它可以更简单,因此我编写了以下代码:

        Dim cmd As New Process
        cmd.StartInfo.FileName = "cmd.exe"
        cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
        cmd.StartInfo.Arguments = "/C dir /b/s Roey.png > 
        C:\Users\ירין\Desktop\Roeyyy\path.txt"
        cmd.Start()
        cmd.WaitForExit()

我跑步时

    "dir /b/s Roey.png > 
    C:\Users\ירין\Desktop\Roeyyy\path.txt"

在CMD上它完美地工作,所以为什么它在这里不起作用? :(

2 个答案:

答案 0 :(得分:1)

我发现了this

Dim MyFilePath As String = Directory.GetFiles([SomePath], "*.png", SearchOption.AllDirectories).
     Where(Function(f) f.Contains("Roey.png")).FirstOrDefault()

解决了!

答案 1 :(得分:0)

您是程序员,所以您搜索文件。

Imports System.Runtime.InteropServices
Sub Main
'On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Dirname = InputBox("Enter Dir name")

ProcessFolder DirName

End Sub

Sub ProcessFolder(FolderPath)
    On Error Resume Next
    Set fldr = fso.GetFolder(FolderPath)

    Set Fls = fldr.files

    For Each thing in Fls
         msgbox Thing.Name & " " & Thing.path 
         'fso.copyfile thing.path, "C:\backup"
    Next

    Set fldrs = fldr.subfolders
    For Each thing in fldrs
        ProcessFolder thing.path
    Next

End Sub