【问题标题】:Visual Basic, Capture output from cmdVisual Basic,从 cmd 捕获输出
【发布时间】:2018-10-07 18:45:38
【问题描述】:

抱歉,如果之前有人问过,我发现其他解决方案对我来说太复杂了.. 无论如何,我正在尝试通过 cmd 在 Visual Basic 代码中搜索图像,并将图像路径保存为字符串,但我似乎无法正确捕获 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 上效果很好,为什么它在这里不起作用? :(

【问题讨论】:

  • 这里有很多问题。 "/C dir /b/s Roey.png" => 这应该是"/C Roey.png dir /B /S".StartInfo.WorkingDirectory = [SomePath] => 指定开始枚举的目录。 .StartInfo.RedirectStandardOutput = True => 你需要重定向StdOut => 这样做.StartInfo.UseShellExecute = False,因为默认是True,它不会工作。 Dim SR As StreamReader = cmd.StandardOutputWhile (imageLocation = String.Empty) imageLocation = SR.ReadLine End While。容易出错。使用Directory.GetFiles()Directory.EnumeratetFiles()
  • idk 为什么但是当我在 cmd 上运行以下命令时,它工作正常。 '"dir /b/s Roey.png > C:\Users\ירין\Desktop\Roeyyy\path.txt"',但是当我写它时,它不起作用,现在更新帖子..
  • CMD.EXE 是一个程序。它解释命令并执行程序。你应该做什么。一行来替换这一切:Dim MyFilePath As String = Directory.GetFiles([SomePath], "*.png", SearchOption.AllDirectories).Where(Function(f) f.Contains("Roey.png")).FirstOrDefault() 其中[SomePath] 是枚举的基本目录。 ==> 第一条评论有错误:应该是:“/C dir Roey.png /B /S”

标签: vb.net cmd capture-output


【解决方案1】:

我找到this

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

解决了!

【讨论】:

  • 嗯,这样更好。仍然不是最好的,只需将“roey.png”作为第二个参数传递。搜索模式也可以是准确的文件名。
  • 看起来与@Jimi 的评论相同。
【解决方案2】:

你是一名程序员,所以你搜索文件。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多