运行 相对路径中的批处理文件?

Running a batch file in relative path?

有一个批处理文件,我想在按下按钮时 运行 它。 当我使用绝对(完整)路径时,我的代码工作正常。但是使用相对路径会导致发生异常。 这是我的代码:

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();
}

和引发的异常:

The system cannot find the file specified.

批处理文件所在目录为:

C:\Users\GntS\myProject\bin\x64\Release\myBatchFiles\BAT1\f1.bat

输出.exe文件位于:

C:\Users\GntS\myProject\bin\x64\Release

我进行了搜索,none 个结果对我有帮助。 运行 相对路径中的批处理文件的正确方法是什么?!

批处理文件将相对于工作目录(即 f1.bat)

但是,您的工作目录应该是绝对路径。不能保证您的应用程序的当前路径(可能在 .lnk 中设置)。特别是它不是 exe 路径。

因此,您应该使用从 AppDomain.CurrentDomain.BaseDirectory(或任何其他众所周知的方法)获得的 exe 文件路径来构建批处理文件 and/or 工作目录的路径。

最后 - 使用 Path.Combine 确定格式正确的路径。

根据 JeffRSon 的回答和 MaciejLosKevinGosse 的评论,我的问题是解决如下:

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"; 

另一种方法是:

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"; 

我在这里报告希望对某人有所帮助。