5,317,180 members and growing! (22,709 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate License: The Code Project Open License (CPOL)

Bat file compiler

By Giorgi Dalakishvili

An article deskribing how to convert bat file to executable
C# 2.0, C#, Windows, .NET, .NET 2.0VS2005, Visual Studio, Dev

Posted: 17 Jun 2007
Updated: 13 Feb 2008
Views: 43,204
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
41 votes for this Article.
Popularity: 6.08 Rating: 3.77 out of 5
5 votes, 12.5%
1
1 vote, 2.5%
2
6 votes, 15.0%
3
6 votes, 15.0%
4
22 votes, 55.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Contents

Introduction

This article shows how to compile a bat file into an executable file. The compiled executable can run without showing a windows 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 bat file is quite tricky and weird so I call this program a "Mock compiler". 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 instance of 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


Mvp

Occupation: Software Developer
Location: Georgia Georgia

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 41 (Total in Forum: 41) (Refresh)FirstPrevNext
Subject  Author Date 
QuestionExe shown codemembermohit kumar paliwal20:15 19 Feb '08  
GeneralUnusefullmemberIzzet Kerem Kusmezer22:09 13 Feb '08  
GeneralRe: G E N I A L, Sir !!!!!!!!!!memberGiorgi Dalakishvili20:49 14 Nov '07  
GeneralTemp filenamememberGuido_d22:38 5 Nov '07  
GeneralRe: Temp filenamememberGiorgi Dalakishvili22:44 5 Nov '07  
AnswerRe: Temp filenamememberlvorrtax14:09 14 Nov '07  
GeneralGood Idea.membernorm .net21:50 5 Nov '07  
GeneralRe: Good Idea.memberGiorgi Dalakishvili22:44 5 Nov '07  
GeneralThat...memberMuammar©20:57 10 Sep '07  
GeneralInteresting...memberPIEBALDconsult5:54 22 Aug '07  
GeneralRe: Interesting...memberGiorgi Dalakishvili5:58 22 Aug '07  
GeneralRe: Interesting...memberMartyK200722:47 23 Sep '07  
GeneralRe: Interesting...mvpJ4amieC0:02 11 Oct '07  
GeneralRe: Interesting...memberMartyK20070:06 11 Oct '07  
GeneralRe: Interesting...memberogrig15:05 11 Oct '07  
GeneralRe: Interesting...memberMartyK200723:53 11 Oct '07  
GeneralRe: Interesting...memberPCoffey10:23 13 Feb '08  
GeneralIt's pefect if encryption function addedmemberfrx22:26 23 Jul '07  
General[Message Deleted]memberGiorgi Dalakishvili0:12 5 Aug '07  
GeneralRe: It's pefect if encryption function addedmvptoxcct3:24 6 Aug '07  
GeneralRe: It's pefect if encryption function addedmemberGiorgi Dalakishvili3:44 6 Aug '07  
GeneralRe: It's pefect if encryption function addedmvptoxcct3:49 6 Aug '07  
GeneralMemoryStreammemberwindrago13:01 3 Jul '07  
GeneralRe: MemoryStreammemberGiorgi Dalakishvili21:52 3 Jul '07  
AnswerRe: MemoryStreammemberwindrago10:38 6 Jul '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:
Copyright 2007 by Giorgi Dalakishvili
Everything else Copyright © CodeProject, 1999-2008
Web12 | Advertise on the Code Project