Showing posts with label embed vbscript exe compile wrapper. Show all posts
Showing posts with label embed vbscript exe compile wrapper. Show all posts

Monday, August 1, 2011

Embed and run VBscript. Convert VBScript to executable (C#)

First Create empty console C# project.

Next, add your script file to project's resources.
In VS2010 you can do it with:
RMB on project name->Properties->Resources->Add Resource->Add New Text File

Now you can get script's content to save and run it.
Source code is quite simple:

To reference script content I use:
Properties.Resources.MyEmbeddedScript
where MyMbeddedScript is name of resource.

Get some random temporary file name:
string scriptFileName = Path.GetTempFileName().Replace(".tmp",".vbs");

Next save and run script:
File.WriteAllText(scriptFileName, content);
startedProcess = Process.Start(scriptFileName);

To run a script as other user you can use this method:
RunAs without password prompt

Any other script (.js, .vbs, .ahk) can be easily embedded into .exe-file in this way.

Full source code:
using System;
using System.Security;
using System.Diagnostics;
using System.IO;

namespace scriptEmbed
{
    class Program
    {
        static int Main(string[] args)
        {
            return RunScript(Properties.Resources.MyEmbeddedScript);
        }
        static int RunScript(string content)
        {
            string scriptFileName = Path.GetTempFileName().Replace(".tmp",".vbs");
            Process startedProcess;
            try
            {
                File.WriteAllText(scriptFileName, content);
                startedProcess = Process.Start(scriptFileName);
                
                while (!startedProcess.HasExited) ;

                File.Delete(scriptFileName);
                
                return startedProcess.ExitCode;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return 1;
            }
        }
        static string GetTempFolder()
        {
            return System.Environment.GetEnvironmentVariable("TEMP");
        }
    }

}