Reputation: 647
There is a batch file which I want to run it when I press the button. My code works fine when I use absolute (full) path. But using relative path causes to occur an exception. This is my code:
private void button1_Click(object sender, EventArgs e)
{
//x64
System.Diagnostics.Process batchFile_1 = new System.Diagnostics.Process();
batchFile_1.StartInfo.FileName = @"..\myBatchFiles\BAT1\f1.bat";
batchFile_1.StartInfo.WorkingDirectory = @".\myBatchFiles\BAT1";
batchFile_1.Start();
}
and the raised exception:
The system cannot find the file specified.
The directory of the batch file is:
C:\Users\GntS\myProject\bin\x64\Release\myBatchFiles\BAT1\f1.bat
The output .exe
file is located in:
C:\Users\GntS\myProject\bin\x64\Release
I searched and none of the results helped me. What is the correct way to run a batch file in relative path?!
Upvotes: 0
Views: 1541
Reputation: 647
According to JeffRSon`s answer and comments by MaciejLos and KevinGosse my problem was solved as below:
string executingAppPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
batchFile_1.StartInfo.FileName = executingAppPath.Substring(0, executingAppPath.LastIndexOf('\\')) + "\\myBatchFiles\\BAT1\\f1.bat";
batchFile_1.StartInfo.WorkingDirectory = executingAppPath.Substring(0, executingAppPath.LastIndexOf('\\')) + "\\myBatchFiles\\BAT1";
An alternative way is:
string executingAppPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
batchFile_1.StartInfo.FileName = executingAppPath.Substring(6) + "\\myBatchFiles\\BAT1\\f1.bat";
batchFile_1.StartInfo.WorkingDirectory = executingAppPath.Substring(6) + "\\myBatchFiles\\BAT1";
I report it here hoping help somebody.
Upvotes: 0
Reputation: 11176
The batch file would be relative to the working directory (i.e. f1.bat)
However, your working directory should be an absolute path. It is not guaranteed whichever path is current for your application (may be set in .lnk). In particular it's not the exe path.
Sou you should use the path of your exe file as obtained from AppDomain.CurrentDomain.BaseDirectory (or any other well known method) to build the path of your batch file and/or working directory.
Finally - use Path.Combine to determine a correctly formatted path.
Upvotes: 2