我是控制台应用程序的新手。我需要从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
但我无法从控制台应用中获取返回值。有什么问题可以解决?
答案 0 :(得分:2)
这不是将参数传递给VB.NET控制台程序的方式(如您所见here)。
一个例子:
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
下,您只需要将要传递的参数放到控制台应用程序中。
依靠简单的临时文件,您可以向调用程序返回不止一个整数。例如:
CONSOLE PROGRAM:
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
答案 1 :(得分:2)
您无法原生地返回两个单独的参数you are limited A 32-bit signed integer
我能想到这样做的唯一方法是,如果你有两个数值,你可以保证每个小于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