Click here to Skip to main content
6,632,966 members and growing! (20,276 online)
Email Password   helpLost your password?
Languages » C# » How To     Intermediate License: The Code Project Open License (CPOL)

Bat file compiler

By Giorgi Dalakishvili

An article deskribing how to convert a bat file to an executable.
C# 2.0, Windows, .NET 2.0VS2005, Dev
Posted:17 Jun 2007
Updated:13 Feb 2008
Views:63,855
Bookmarked:89 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
43 votes for this article.
Popularity: 6.15 Rating: 3.77 out of 5
5 votes, 11.9%
1
1 vote, 2.4%
2
7 votes, 16.7%
3
6 votes, 14.3%
4
23 votes, 54.8%
5

Contents

Introduction

This article shows how to compile a bat file into an executable file. The compiled executable can run without showing a window, and you can pass command line parameters to it as you would pass them to the bat file.

How the program works

The way this program compiles a bat file is quite tricky and weird, so I call this program a "Mock compiler". The bat file is not even parsed. This program creates another program, and adds the specified bat file as an embedded file in that program. When the generated program is executed, it extracts the embedded bat file to a temp folder, and runs it using the Process class. Simple, isn't it?

Using the code

In order to create another program from your application, you will need to create an instance of the CSharpCodeProvider class. The code snippet below shows how to do it:

using (CSharpCodeProvider code=new CSharpCodeProvider())
{
    CompilerParameters compar = new CompilerParameters();

    string option = "/target:winexe";

    // Set the icon for executable
    if (Properties.Settings.Default.Customicon && 
        File.Exists(Properties.Settings.Default.iconpath))
    {
       option += " " + "/win32icon:" + "\"" + 
                 Properties.Settings.Default.iconpath + "\"";
    }

    compar.CompilerOptions = option;
    compar.GenerateExecutable = true;
    compar.IncludeDebugInformation = false;

    //Add the bat file as an embedded resource
    if (File.Exists(filepath))
    {
       compar.EmbeddedResources.Add(filepath); 
    }

    compar.OutputAssembly = path;
    compar.GenerateInMemory = false; 

    //Add references
    compar.ReferencedAssemblies.Add("System.dll");
    compar.ReferencedAssemblies.Add("System.Data.dll");
    compar.ReferencedAssemblies.Add("System.Deployment.dll");
    compar.ReferencedAssemblies.Add("System.Drawing.dll");
    compar.ReferencedAssemblies.Add("System.Windows.Forms.dll");
    compar.ReferencedAssemblies.Add("System.Xml.dll");

    compar.TreatWarningsAsErrors = false;

    //Compile it
    //The code is included in the executable as a resource
    CompilerResults res = 
              code.CompileAssemblyFromSource(compar, Properties.Resources.Program);

    if (res.Errors.Count > 0)
    {
       result = false;
    }
    else
       result = true;
    }

When you run the generated executable, it will extract the bat file, process the command line arguments if any, and run it. If specified, the bat file will run without creating any window. Here is the code that shows how this is accomplished.

//This code requires System.Reflection namespace
//Extracts the bat file
private void extract()
{
    string name = Assembly.GetExecutingAssembly().GetManifestResourceNames()[0];
    hide = name.EndsWith("hideit.bat");

    Stream theResource = Assembly.GetExecutingAssembly().GetManifestResourceStream(name);

    BinaryReader br = new BinaryReader(theResource);
    FileStream fs = new FileStream(Environment.GetEnvironmentVariable("TEMP") + 
                    "\\it.bat", FileMode.Create);

    byte[] bt = new byte[theResource.Length];
    theResource.Read(bt, 0, bt.Length);
    fs.Write(bt, 0, bt.Length);

    br.Close();
    fs.Close();
}

//Process command line arguments
private string buildargument(string[] args)
{
    StringBuilder arg = new StringBuilder();

    for (int i = 0; i < args.Length; i++)
    {
       arg.Append(args[i] + " ");
    }

    return arg.ToString();
}

//Start the process
private void start(string[] args)
{
    ProcessStartInfo info = new ProcessStartInfo();
    info.FileName = Environment.GetEnvironmentVariable("TEMP") + "\\it.bat";

    //Specify argument
    info.Arguments = buildargument(args);

    //Hide the window if specified
    info.CreateNoWindow = hide;
    if (hide)
    {
        info.WindowStyle = ProcessWindowStyle.Hidden;
    }

    //Set the working directory for the bat file. This is important as the
    //bat file might use relative path
    info.WorkingDirectory = Application.StartupPath;

    //At last start the process
    Process proc = new Process();
    proc.StartInfo = info;
    proc.Start();
}

Points of interest

The way this program compiles bat files is quite tricky and a little bit strange.

History

  • 17 June, 2007 - Initial release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Giorgi Dalakishvili


Member

Occupation: Software Developer
Location: Georgia Georgia

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 40 (Total in Forum: 40) (Refresh)FirstPrevNext
QuestionExe shown code Pinmembermohit kumar paliwal20:15 19 Feb '08  
GeneralUnusefull PinmemberIzzet Kerem Kusmezer22:09 13 Feb '08  
GeneralRe: G E N I A L, Sir !!!!!!!!!! PinmemberGiorgi Dalakishvili20:49 14 Nov '07  
GeneralTemp filename PinmemberGuido_d22:38 5 Nov '07  
GeneralRe: Temp filename PinmemberGiorgi Dalakishvili22:44 5 Nov '07  
AnswerRe: Temp filename Pinmemberlvorrtax14:09 14 Nov '07  
GeneralGood Idea. Pinmembernorm .net21:50 5 Nov '07  
GeneralRe: Good Idea. PinmemberGiorgi Dalakishvili22:44 5 Nov '07  
GeneralInteresting... PinmemberPIEBALDconsult5:54 22 Aug '07  
GeneralRe: Interesting... PinmemberGiorgi Dalakishvili5:58 22 Aug '07  
GeneralRe: Interesting... PinmemberMartyK200722:47 23 Sep '07  
GeneralRe: Interesting... PinmvpJ4amieC0:02 11 Oct '07  
GeneralRe: Interesting... PinmemberMartyK20070:06 11 Oct '07  
GeneralRe: Interesting... Pinmemberogrig15:05 11 Oct '07  
GeneralRe: Interesting... PinmemberMartyK200723:53 11 Oct '07  
GeneralRe: Interesting... PinmemberPCoffey10:23 13 Feb '08  
GeneralIt's pefect if encryption function added Pinmemberfrx22:26 23 Jul '07  
General[Message Deleted] PinmemberGiorgi Dalakishvili0:12 5 Aug '07  
GeneralRe: It's pefect if encryption function added Pinmvptoxcct3:24 6 Aug '07  
GeneralRe: It's pefect if encryption function added PinmemberGiorgi Dalakishvili3:44 6 Aug '07  
GeneralRe: It's pefect if encryption function added Pinmvptoxcct3:49 6 Aug '07  
GeneralMemoryStream Pinmemberwindrago13:01 3 Jul '07  
GeneralRe: MemoryStream PinmemberGiorgi Dalakishvili21:52 3 Jul '07  
AnswerRe: MemoryStream Pinmemberwindrago10:38 6 Jul '07  
GeneralVery nice PinmemberT1TAN23:13 27 Jun '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 13 Feb 2008
Editor: Smitha Vijayan
Copyright 2007 by Giorgi Dalakishvili
Everything else Copyright © CodeProject, 1999-2009
Web11 | Advertise on the Code Project