Click here to Skip to main content
15,889,863 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I created a visual basic windows form application using Visual Studio 2013.
I create a text file in add new item and rename it to run.bat.
And also created a button.
My question is how can i execute the batch file when i click the button?
This code doesn't work:

VB
Process.Start("run.bat")


ScreenShot
Posted
Updated 30-Oct-15 5:36am
v4
Comments
CHill60 30-Oct-15 9:16am    
When you say "doesn't work" - are there any error messages?
Leo Chapiro 30-Oct-15 9:29am    
Use try/catch block around of Process.Start("run.bat") and provide the exception (assumedly "FileNoutFound") - possibly you need the whole path to the batch file!

This works fine for me IF I also set the File Properties on the batch file correctly ... Copy to Output Directory needs to be set to Copy always

OR

You need to provide a path to the batch file e.g.
Process.Start("c:\temp\run.bat")
 
Share this answer
 
Not in front of my dev machine but I think the error you will get is file not found.

You have asked your program to execute run.bat but not told it where run.bat is actually stored.

Try this:
VB
Dim path As String
   path = System.IO.Path.GetDirectoryName( _
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
Process.start(path & "\Run.bat")


You may not need the \
The path will be set wherever the exe is ran from, so the batch file will have to be in the same folder. EG: c:\Myprog\Myexe.exe and c:\Myprog\Run.bat
 
Share this answer
 
v2
hope below code will help you

//To create a batch file
System.IO.StreamWriter SW = new System.IO.StreamWriter("FileName.bat");
SW.WriteLine("FileContent");
SW.Flush();
SW.Close();
SW.Dispose();
SW = null;

//To Run the batch file use below command
System.Diagnostics.Process.Start("FileName.bat");
 
Share this answer
 
Comments
CHill60 30-Oct-15 9:52am    
Apart from the obvious problem that this is C# code and not VB.NET, this only works because you have not provided a path for Filename.bat so it is created by default in the \bin\Debug folder (or equivalent).
It's also not a particularly good example of how to use StreamWriter in C# - use a using block.

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900