【问题标题】:Return a value from vbscript function in c#从 c# 中的 vbscript 函数返回一个值
【发布时间】:2012-12-29 08:31:03
【问题描述】:

我正在 c# 中从我的代码中执行一个 .vbs 文件,以检查用户的真实性。我正在传递用户名和密码值,登录时单击 .vbs 将运行并对用户进行身份验证。如果用户不真实,则 vbs 中的函数返回一个值,我如何在 c# 的代码中获取该值并使用它在应用程序的 UI 中显示正确的错误消息。 请帮忙..

【问题讨论】:

  • 你是如何运行 VBS 的?你能解释一些代码来澄清吗?
  • Process.Start("Execute.vbs");我正在执行 vbs 文件。我现在需要的是从 winform UI 传递 uname 和 pwd 的值以在 Execute 中运行,该函数将返回一个字符串值,我必须再次在 UI 中显示它。

标签: winforms c#-4.0 vbscript


【解决方案1】:

不是展示产品代码,而是展示

  1. “原则上”/它是如何工作的
  2. 您必须在文档中查找哪些关键字/组件

demo.cs:

using System;
using System.Diagnostics;

namespace Demo
{
    public class Demo
    {
        public static void Main(string [] args) {
            string user  = "nix";
            if (1 <= args.Length) {user = args[0];};
            string passw = "nix";
            if (2 <= args.Length) {passw = args[1];};
            string cscript = "cscript";
            string cmd = string.Format("\"..\\vbs\\auth.vbs\" {0} {1}", user, passw);
            System.Console.WriteLine("{0} {1}", cscript, cmd);

            Process process = new Process();
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.FileName = "cscript.exe";
            process.StartInfo.Arguments = cmd;
            try {
              process.Start();
              System.Console.WriteLine(process.StandardOutput.ReadToEnd());
              System.Console.WriteLine(process.ExitCode);
            } catch (Exception ex) {
              System.Console.WriteLine(ex.ToString());
            }
        }
    }
}

auth.vbs:

Option Explicit

Dim nRet : nRet = 2
If WScript.Arguments.Count = 2 Then
   If "user" = WScript.Arguments(0) And "passw" = WScript.Arguments(1) Then
      WScript.Echo "ok"
      nRet = 0
   Else
      WScript.Echo "fail"
      nRet = 1
   End If
Else
   WScript.Echo "bad"
End If
WScript.Quit nRet

输出:

demo.exe
cscript "..\vbs\auth.vbs" nix nix
fail

1

demo.exe user passw
cscript "..\vbs\auth.vbs" user passw
ok

0

也许您可以通过忘记返回文本并仅使用 .Exitcode 来简化事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 2011-02-05
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多