调试从C#

问题描述:

一个VBScript我有以下代码:调试从C#

Process scriptProc = new Process(); 
       scriptProc.StartInfo.FileName = @"cscript"; 
       scriptProc.StartInfo.WorkingDirectory = @"C:\MyPath\"; 
       scriptProc.StartInfo.Arguments = "filename.vbs //X"; 
       scriptProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
       scriptProc.Start(); 
       scriptProc.WaitForExit(); 
       scriptProc.Close(); 

我VBS其中由// X属性指定的编辑器(Visual Studio中)打开,但如果剧本没有这只是打开语法错误,如果我有脚本错误,它不会在编辑器中打开,这基本上使得调试器的使用变得冗余。

有什么办法可以使用C#调试VBScript吗?

下面的代码使用@Ekkehard.Horner方法。编译它,然后将.vbs文件拖放到可执行文件以测试文件是否有语法错误:

using System; 
using System.IO; 
using System.Reflection; 
using System.Windows.Forms; 
using System.Runtime.InteropServices; 
// Add reference to COM Microsoft Script Control 1.0 
// Code works for .Net 2.0 and above 
class Program 
{ 
    static void Main(string[] args) 
    { 
     // Check whether a file was dragged onto executable 
     if (args.Length != 1) 
     { 
      MessageBox.Show("Drag'n'drop .vbs file onto this executable to check syntax"); 
      return; 
     } 
     MessageBox.Show("Syntax will be checked for\r\n" + args[0]); 
     String vbscode = ""; 
     // Read the content of the file 
     try 
     { 
      StreamReader sr = new StreamReader(args[0]); 
      vbscode = sr.ReadToEnd(); 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show("File reading error " + e.Message); 
      return; 
     } 
     // Add statement raising runtime error -2147483648 in the first line to ScriptControl 
     int hr = 0; 
     try 
     { 
      vbscode = "Err.Raise &H80000000\r\n" + vbscode; 
      MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl(); 
      sc.Language = "VBScript"; 
      sc.AddCode(vbscode); 
     } 
     catch (Exception e) 
     { 
      hr = Marshal.GetHRForException(e); 
      // First line of code executed if no syntax errors only 
      if (hr == -2147483648) 
      { 
       // Run time error -2147483648 shows that execution started without syntax errors 
       MessageBox.Show("Syntax OK"); 
      } 
      else 
      { 
       // Otherwise there are syntax errors 
       MessageBox.Show("Syntax error"); 
      }    
     } 
    } 
} 
+0

工程就像一个魅力!非常感谢! – 2014-09-23 06:36:31

回答你的问题,不,我恐怕你不能在C#的调试环境中调试VBScript。尝试使用类似http://www.vbsedit.com的东西直接调试脚本。首先在C#中启动脚本,这会让事情变得复杂。

+0

我无法获取脚本中的错误(如果有)?如果我的脚本正确,它会运行吗? 。你是这个意思吗?只要确保我了解你。 – 2014-09-22 10:03:03

+0

我修改了我的答案。关键是你应该调试你的脚本,而不用担心现在的C#位。在一天结束时,C#部分是微不足道的,而不是问题的根源。你的问题更多的是学习如何在Visual Studio或任何工具中调试VBScript。 – krisdyson 2014-09-22 10:08:17

调试器是处理运行时错误的工具。所以它不能用来检查编译时错误。

不幸的是,c | wscript.exe脚本主机没有像Perl的-c(语法检查)这样的选项。运行cscript maybebad.vbs捕捉语法错误可能不方便,如果无意中/不知情地执行完美关机/格式化我的硬盘/ ...脚本。你可以编写一个脚本,前面加上 前缀的maybebad.vbs的代码Execute(Global)

MS ScriptControl可以用来避免炮击;我不确定,这是否会简化您的“调试体验”。

+0

感谢您的回答,我仍然在尝试。另外,我认为我应该更多地解释我的问题。所以这里是:我有很多用于测试网页的测试用例的脚本,我需要制作一个应用程序,用户在其中选择一个网页和所需的所有组件(文本框等),并运行我的脚本,但在运行它们之前,我需要检查脚本。 – 2014-09-22 12:46:21