1

The code from this question works fine as below:

var scriptType = Type.GetTypeFromCLSID(Guid.Parse("0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC"));

dynamic obj = Activator.CreateInstance(scriptType, false);
obj.Language = "vbscript";
var vbscript = @"MsgBox(""Hello"");
obj.Eval(vbscript);

But as soon I try to add another line to the script, for example:

var vbscript = @"MsgBox(""Hello"")
                 MsgBox(""World"")";

I get a syntax error when calling obj.Eval(vbsbcript):

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in System.Dynamic.dll

Additional information: Syntax error

I can see that the value of vbscript contains a load of \r\ns for the newlines:

"MsgBox(\"Hello\")\r\nMsgBox(\"World\")"

I tried declaring it with

vbscript = "MsgBox(\"Hello\")" +
            Environment.NewLine +
            "MsgBox(\"World\")";

but with the same results.

Is it possible to run some vbscript stored in a string which contains multiple lines in C#? If so how can this be achieved?

I know it is possible by calling a .vbs file with Process.Start(path), but can it be done directly from a string in the progam without having to depend on another file?

1 Answer 1

1

After the

var vbscript = @"MsgBox(""Hello"")
                 MsgBox(""World"")";

Try to add this

vbscript = vbscript.Replace("\r\n", " & VbCrLf & ");

That should do it.

From docs

Represents a carriage-return character combined with a linefeed character for print and display functions.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Juan, that did it for my example. I am now seeing the same syntax error when I try running theh one-line script Dim test. Do you know why thi might be?
could you share the full script you want to run?
the full script is actually from this question: stackoverflow.com/questions/42610844/… But even trying to run just the 1 line Dim test saved in a string as above produces the syntax error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.