1

我是控制台应用程序的新手。我需要从 Web 应用程序向控制台应用程序传递两个命令行参数,并从控制台应用程序获取返回的结果。

我在这里尝试过

 Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim proc = New Process() With { _
        .StartInfo = New ProcessStartInfo() With { _
        .FileName = "C:\Users\Arun\Documents\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe", _
        .Arguments = TextBox1.Text & " " & TextBox2.Text, _
        .UseShellExecute = False, _
        .RedirectStandardOutput = True, _
        .CreateNoWindow = True _
        } _
   }

        proc.Start()

        proc.WaitForExit()
        Response.Write(proc.ExitCode.ToString())


    End Sub

我的控制台应用程序代码是

Public Function Main(sArgs As String()) As Integer


        Return sArgs(0)


    End Function

但我无法从控制台应用程序获取返回值。有什么问题有人帮忙吗?

4

2 回答 2

2

你不能原生地返回两个单独的参数,你是有限的 32 位有符号整数

我能想到的唯一方法是,如果你有两个可以保证每个小于 16 位的数值,那么你可以通过对其中一个进行位移来将它们组合成一个 32 位的值。

这段代码应该让你开始:

Public Shared Function CombineValues(val1 As Int16, val2 As Int16) As Int32
    Return val1 + (CInt(val2) << 16)
End Function

Public Shared Sub ExtractValues(code As Int32, ByRef val1 As Int16, ByRef val2 As Int16)
    val2 = CShort(code >> 16)
    val1 = CShort(code - (CInt(val2) << 16))
End Sub

用法(控制台):

    'in your console app combine two int16 values into one Int32 to use as the exit code
    Dim exitCode As Int32 = CombineValues(100, 275)
    Debug.WriteLine(exitCode) 'Output: 18022500

用法(调用代码):

    'In the calling app split the exit code back into the original values
    Dim arg1 As Int16
    Dim arg2 As Int16
    ExtractValues(exitCode, arg1, arg2)

    Debug.WriteLine(arg1.ToString + "; " + arg2.ToString) 'Output: 100; 275
于 2013-07-02T10:10:56.557 回答
2

这不是将参数传递给 VB.NET 控制台程序的方式(如您在此处所见)。

一个例子:

Module Module1

    Sub Main()
        For Each arg As String In My.Application.CommandLineArgs
            Console.WriteLine(arg)
        Next
    End Sub

End Module

如果您生成一个仅包含上述代码的控制台项目 EXE (app.exe) 并像这样(从 cmd)调用它:[full_path]app 1 2,您将1 2在屏幕上打印。

因此,您所要做的就是从中检索参数My.Application.CommandLineArgs

-------- 更好地解释了确切要求后的更新

在下面.Arguments,您必须只放置要传递给控制台应用程序的参数。

依靠一个简单的临时文件,您可以向调用程序返回多个整数。例如:

控制台程序:

Dim writer As New System.IO.StreamWriter("temp")

writer.Write("anything")
writer.Close()

调用程序:

Dim reader As New System.IO.StreamReader("temp")
Dim line As String
Do
    line = sr.ReadLine() 'reading anything passed from the console
Loop Until line Is Nothing
reader.Close()

Try
   System.IO.File.Delete("temp")
Catch ex As Exception

End Try
于 2013-07-02T09:23:12.353 回答