简单的软件测试工具——VB.NET [英] Simple software testing tool - VB.NET

查看:54
本文介绍了简单的软件测试工具——VB.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,请不要嘲笑这个:x
我正在尝试在 VB.NET 中创建一个简单的软件测试工具
我创建了一个简单的 C 程序 PROG.EXE,它扫描一个数字并打印 OUTPUT,然后开始构建我的测试仪,它应该执行 PROG.EXE output.txt,所以 PROG.EXE 接受输入从 input.txt 并将输出打印到 output.txt
但我失败了,起初我尝试了 Process.start 然后是 shell 但没有任何效果!
所以我做了这个把戏,VB.NET 代码用这个代码生成一个批处理文件PROG.EXE output.txt,但我又失败了,尽管 VB.NET 创建了批处理文件并执行了,但什么也没发生!但是当我手动运行批处理文件时,我成功了!
我尝试执行批处理文件,然后将 VBCR/LF/CRLF 发送密钥仍然没有任何反应!
怎么了?

ok, please do no laugh at this :x
i'm trying to create a simple software testing tool in VB.NET
i created a simple C program PROG.EXE which scans a number and prints the OUTPUT, and started building my tester, it should execute PROG.EXE output.txt, so PROG.EXE takes input from input.txt and prints the output to output.txt
but i failed, at first i tried Process.start then shell but nothing worked !
so i did this trick, the VB.NET codes generate a batch file with this codes PROG.EXE output.txt, but again i failed, though the VB.NET created the batch file and executes too, but nothing happened ! but when i manually run the batch file i got success !
i tried executing the batchfile then sendkey the VBCR/LF/CRLF still nothing happens !
whats wrong ?

我的 VB.NET 代码,我使用的是 Visual Studio 2010 Professional

Option Explicit On  
Option Strict On  
Public Class Form1  
 Dim strFileName As String

 Private Sub btnRun_Click() Handles btnRun.Click  
  Dim strOutput As String  
  Using P As New Process()  
   P.StartInfo.FileName = strFileName  
   P.StartInfo.Arguments = txtInput.Text  
   P.StartInfo.RedirectStandardOutput = True  
   P.StartInfo.UseShellExecute = False  
  P.StartInfo.WindowStyle = ProcessWindowStyle.Hidden  ' will this hide the console ?
   P.Start()  
   Using SR = P.StandardOutput  
    strOutput = SR.ReadToEnd()  
   End Using  
  End Using  
  txtOutput.Text = strOutput  
 End Sub

 Private Sub btnTarget_Click() Handles btnTarget.Click  
  dlgFile.ShowDialog()  
  strFileName = dlgFile.FileName  
  lblFileName.Text = strFileName  
 End Sub  
End Class  

这是我的 C 代码

#include<stdio.h>  
#include<conio.h>

void main()
{
 int x;
 scanf("%d",&x);
 printf("%d",(x*x));
}

当我在控制台中运行 prog.exe <input.txt> output.txt 时,我的程序运行完美

my program runs perfectly when i run prog.exe <input.txt> output.txt in console

推荐答案

下面是一个完整的示例.您想使用 Process 您尝试过的类,但您需要 RedirectStandardOutput 在进程的 StartInfo.然后你可以阅读流程的StandardOutput.下面的示例是使用 VB 2010 编写的,但对于旧版本的工作方式几乎相同.

Below is a fully working example. You want to use the Process class as you tried but you need to RedirectStandardOutput on the process's StartInfo. Then you can just read the process's StandardOutput. The sample below is written using VB 2010 but works pretty much the same for older versions.

Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//This will hold the entire output of the command that we are running
        Dim T As String

        ''//Create our process object
        Using P As New Process()
            ''//Pass it the EXE that we want to execute
            ''//NOTE: you might have to use an absolute path here
            P.StartInfo.FileName = "ping.exe"

            ''//Pass it any arguments needed
            ''//NOTE: if you pass a file name as an argument you might have to use an absolute path
            P.StartInfo.Arguments = "127.0.0.1"

            ''//Tell the process that we want to handle the commands output stream
            ''//NOTE: Some programs also write to StandardError so you might want to watch that, too
            P.StartInfo.RedirectStandardOutput = True

            ''//This is needed for the previous line to work
            P.StartInfo.UseShellExecute = False

            ''//Start the process
            P.Start()

            ''//Wrap a StreamReader around the standard output
            Using SR = P.StandardOutput
                ''//Read everything from the stream
                T = SR.ReadToEnd()
            End Using
        End Using

        ''//At this point T will hold whatever the process with the given arguments kicked out
        ''//Here we are just dumping it to the screen
        MessageBox.Show(T)
    End Sub
End Class

编辑

这是从 StandardOutputStandardError 读取的更新版本.这次它异步读取.该代码调用 CHOICE exe 并传递一个无效的命令行开关,这将触发写入 StandardError 而不是 StandardOutput.对于您的程序,您可能应该同时监视两者.此外,如果您将文件传递到程序中,请确保指定文件的绝对路径,并确保如果文件路径中有空格,则将路径用引号括起来.

Here is an updated version that reads from both StandardOutput and StandardError. This time it reads asynchronously. The code calls the CHOICE exe and passes an invalid command line switch which will trigger writing to StandardError instead of StandardOutput. For your program you should probably monitor both. Also, if you're passing a file into the program make sure that you are specifying the absolute path to the file and make sure that if you have spaces in the file path that you are wrapping the path in quotes.

Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//This will hold the entire output of the command that we are running
        Dim T As String

        ''//Create our process object
        Using P As New Process()
            ''//Pass it the EXE that we want to execute
            ''//NOTE: you might have to use an absolute path here
            P.StartInfo.FileName = "choice"

            ''//Pass it any arguments needed
            ''//NOTE: if you pass a file name as an argument you might have to use an absolute path
            ''//NOTE: I am passing an invalid parameter to show off standard error
            P.StartInfo.Arguments = "/G"

            ''//Tell the process that we want to handle the command output AND error streams
            P.StartInfo.RedirectStandardOutput = True
            P.StartInfo.RedirectStandardError = True

            ''//This is needed for the previous line to work
            P.StartInfo.UseShellExecute = False

            ''//Add handlers for both of the data received events
            AddHandler P.ErrorDataReceived, AddressOf ErrorDataReceived
            AddHandler P.OutputDataReceived, AddressOf OutputDataReceived

            ''//Start the process
            P.Start()

            ''//Start reading from both error and output
            P.BeginErrorReadLine()
            P.BeginOutputReadLine()

            ''//Signal that we want to pause until the program is done running
            P.WaitForExit()


            Me.Close()
        End Using
    End Sub

    Private Sub ErrorDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Error  : {0}", e.Data))
    End Sub
    Private Sub OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Output : {0}", e.Data))
    End Sub
End Class

如果整个文件路径中有空格,请务必将其放在引号中(实际上,您应该始终将其括在引号中以防万一.)例如,这行不通:

Its important that you put your entire file path in quotes if it has spaces in it (in fact, you should always enclose it in quotes just in case.) For instance, this won't work:

P.StartInfo.FileName = "attrib"
P.StartInfo.Arguments = "C:\Program Files\Windows NT\Accessories\wordpad.exe"

但这将:

P.StartInfo.FileName = "attrib"
P.StartInfo.Arguments = """C:\Program Files\Windows NT\Accessories\wordpad.exe"""

编辑 2

好吧,我是个白痴.我以为您只是将文件名括在尖括号中,例如 <input.txt>[input.txt],我没有意识到您使用的是实际流重定向器!(input.txt 前后的空格会有所帮助.)抱歉造成混乱.

Okay, I'm an idiot. I thought you were just wrapping a filename in angled brackets like <input.txt> or [input.txt], I didn't realize that you were using actual stream redirectors! (A space before and after input.txt would have helped.) Sorry for the confusion.

有两种方法可以使用 Process 对象处理流重定向.首先是手动读取input.txt并将其写入StandardInput,然后读取StandardOutput并将其写入output.txt 但你不想这样做.第二种方法是使用 Windows 命令解释器,cmd.exe,它有一个特殊的参数 /C.传递后,它会为您执行后面的任何字符串.所有流重定向都像您在命令行中键入一样工作.重要的是,您传递的任何命令都包含在引号中,因此与文件路径一起您会看到一些双引号.所以这是一个可以完成所有这些的版本:

There are two ways to handle stream redirection with the Process object. The first is to manually read input.txt and write it to StandardInput and then read StandardOutput and write that to output.txt but you don't want to do that. The second way is to use the Windows command interpreter, cmd.exe which has a special argument /C. When passed it executes any string after it for you. All stream redirections work as if you typed them at the command line. Its important that whatever command you pass gets wrapped in quotes so along with the file paths you'll see some double-quoting. So here's a version that does all that:

Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//Full path to our various files
        Dim FullExePath As String = "C:\PROG.exe"
        Dim FullInputPath As String = "C:\input.txt"
        Dim FullOutputPath As String = "C:\output.txt"

        ''//This creates our command using quote-escaped paths, all completely wrapped in an extra set of quotes
        ''//""C:\PROG.exe" < "C:\input.txt" > "C:\output.txt""
        Dim FullCommand = String.Format("""""{0}"" < ""{1}"" > ""{2}""""", FullExePath, FullInputPath, FullOutputPath)
        ''//Create our process object
        Using P As New Process()
            ''//We are going to use the command shell and tell it to process our command for us
            P.StartInfo.FileName = "cmd"

            ''//The /C (capitalized) means "execute whatever else is passed"
            P.StartInfo.Arguments = "/C " & FullCommand

            ''//Start the process
            P.Start()

            ''//Signal to wait until the process is done running
            P.WaitForExit()
        End Using

        Me.Close()
    End Sub
End Class

编辑 3

您传递给 cmd/C 的整个命令参数需要包含在一组引号中.因此,如果您连接它,它将是:

The entire command argument that you pass to cmd /C needs to be wrapped in a set of quotes. So if you concat it it would be:

Dim FullCommand as String = """""" & FullExePath & """" & " <""" & FullInputPath & """> " & """" & FullOutputPath & """"""

您传递的实际命令如下所示:

Here's what the actual command that you pass should look like:

cmd /C ""C:\PROG.exe" < "C:\INPUT.txt" > "C:\output.txt""

这是一个完整的代码块.我已经重新添加了错误和输出阅读器,以防万一您遇到权限错误或其他问题.因此,请查看立即窗口以查看是否有任何错误被踢出.如果这不起作用,我不知道该告诉你什么.

Here's a full code block. I've added back the error and output readers just in case you're getting a permission error or something. So look at the Immediate Window to see if any errors are kicked out. If this doesn't work I don't know what to tell you.

Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//Full path to our various files
        Dim FullExePath As String = "C:\PROG.exe"
        Dim FullInputPath As String = "C:\INPUT.txt"
        Dim FullOutputPath As String = "C:\output.txt"

        ''//This creates our command using quote-escaped paths, all completely wrapped in an extra set of quotes
        Dim FullCommand As String = """""" & FullExePath & """" & " <""" & FullInputPath & """> " & """" & FullOutputPath & """"""
        Trace.WriteLine("cmd /C " & FullCommand)


        ''//Create our process object
        Using P As New Process()
            ''//We are going to use the command shell and tell it to process our command for us
            P.StartInfo.FileName = "cmd"

            ''//Tell the process that we want to handle the command output AND error streams
            P.StartInfo.RedirectStandardError = True
            P.StartInfo.RedirectStandardOutput = True

            ''//This is needed for the previous line to work
            P.StartInfo.UseShellExecute = False

            ''//Add handlers for both of the data received events
            AddHandler P.ErrorDataReceived, AddressOf ErrorDataReceived
            AddHandler P.OutputDataReceived, AddressOf OutputDataReceived

            ''//The /C (capitalized) means "execute whatever else is passed"
            P.StartInfo.Arguments = "/C " & FullCommand

            ''//Start the process
            P.Start()


            ''//Start reading from both error and output
            P.BeginErrorReadLine()
            P.BeginOutputReadLine()


            ''//Signal to wait until the process is done running
            P.WaitForExit()
        End Using

        Me.Close()
    End Sub
    Private Sub ErrorDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Error  : {0}", e.Data))
    End Sub
    Private Sub OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Output : {0}", e.Data))
    End Sub
End Class

这篇关于简单的软件测试工具——VB.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆