如何在C#应用程序中调用VBScript文件?
题
我需要在C#Windows应用程序中调用 VBScript 文件(.vbs文件扩展名) 。 我怎样才能做到这一点?
有一个加载项可以访问VBScript文件 在Visual Studio中。 但我需要在后面的代码中访问脚本。怎么做?
解决方案
以下代码将执行VBScript脚本,没有提示或错误,也没有shell徽标。
System.Diagnostics.Process.Start(@"cscript //B //Nologo c:\scripts\vbscript.vbs");
使用更复杂的技术:
Process scriptProc = new Process();
scriptProc.StartInfo.FileName = @"cscript";
scriptProc.StartInfo.WorkingDirectory = @"c:\scripts\"; //<---very important
scriptProc.StartInfo.Arguments ="//B //Nologo vbscript.vbs";
scriptProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //prevent console window from popping up
scriptProc.Start();
scriptProc.WaitForExit(); // <-- Optional if you want program running until your script exit
scriptProc.Close();
使用 StartInfo
属性,您可以非常精细地访问流程设置。
如果您希望通过以下方式显示窗口等,则需要使用 Windows脚本宿主脚本程序。您也可以尝试直接执行 cscript
,但在某些系统上它只会启动编辑器:)
其他提示
另一种方法是创建VB.NET类库项目,将VBScript代码复制到VB.NET类文件中,并从C#程序引用VB.NET类库。
您需要修复VBScript和VB.NET之间的任何差异(应该很少)。
这里的优势在于您将在进程中运行代码。
这是权限问题。您的应用程序appPool必须在2008年以最高权限级别运行。身份必须是管理员。
你的意思是你试图从C#运行一个vbs文件?
可以像从C#代码运行任何其他程序:
Process.Start(path);
但是你必须确保它不会要求任何东西,并且它正在使用解释器的命令行版本运行:
Process.Start("cscript path\\to\\script.vbs");
为了搜索者的利益,我发现了这个 post ,它给出了一个明确的答案(特别是如果你有参数)。测试过 - 似乎工作正常。
string scriptName = "myScript.vbs"; // full path to script
int abc = 2;
string name = "Serrgggio";
ProcessStartInfo ps = new ProcessStartInfo();
ps.FileName = "cscript.exe";
ps.Arguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", scriptName, abc, name);
//This will equate to running via the command line:
// > cscript.exe "myScript.vbs" "2" "Serrgggio"
Process.Start(ps);
不隶属于 StackOverflow