Menimitz
Menimitz

Reputation: 11

Suggestions on calling a batch file from a C# program

I am very new to using C# and am only using it currently for work purposes. I am currently editing an existing application and am trying to add a function that will call a batch file that I have written. This batch file runs a CLI program and does some error level checks to ensure the program executed correctly and reports any errors to the command prompt. I do not wish to rewrite this function in C# because this batch file is useful to me when I am performing this task without the main program. However, if rewriting this batch file's functions in C# is needed I would not know how to go about doing it.

I found this code online to run my batch file, and it works quite well:

        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.EnableRaisingEvents = false;
        proc.StartInfo.FileName = "C:mypath\\mybatfile.bat";
        proc.Start();

My only problem with this code is that it requires me to set this path before I deploy the application. I will be distributing this application to a few other machines, and may eventually distribute it to many more. I would really like to find a way to somehow link this path to where the program is saved and just include this batch file in the resources of the application.

This all may be very off base, and any direction provided will be greatly appreciated.

I have very little knowledge of terminology used in C# and other PC programming as most of my experience is in uControllers.

EDIT: My program is a GUI .xaml application. I have also decided that I am open to rewriting my batch file in C# because I also have some paths in my batch file that I forgot about. is there any way to run a command prompt application and pass command line arguments and check error-levels easily?

EDIT 2: I am adding this just to help anyone that comes along this thread in the future. this is how I eventually fixed my problem, using a suggestion from Dantix below:

        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.EnableRaisingEvents = false;
        string bat_path = System.Reflection.Assembly.GetExecutingAssembly().Location; 
        proc.StartInfo.FileName = bat_path.Replace("\\myAppName.exe, "") + "\\myBatchFile.bat";
        proc.Start();

Thanks for all the help!

Upvotes: 1

Views: 419

Answers (2)

user1436916
user1436916

Reputation:

You could use Application.StartupPath to Get the path for the executable file that started the application, not including the executable name.

According to your requirement it may be
proc.StartInfo.FileName = Application.StartupPath +"\\mybatfile.bat";

Upvotes: 3

Kaio Barbosa
Kaio Barbosa

Reputation: 41

Maybe you could use the application settings or if your program is a console application, you could use command-line arguments

Upvotes: 0

Related Questions