2017-07-08 135 views
0

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

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

和引发的异常:

该系统找不到指定的文件。

批处理文件的目录是:

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

输出.exe文件位于:

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

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

+2

您可以获取可执行文件路径,请参阅:[如何确定执行应用程序的路径](https://msdn.microsoft.com/en-us/library/aa457089.aspx) –

+0

@MaciejLos是的,我可以。但是...... \\或。\\呢?我总是成功地使用它们。 – GntS

+2

根据文档,如果'UseShellExecute'为true(并且这是默认值),则相对于工作目录搜索可执行文件。这意味着你正在尝试执行'。\ myBatchFiles \ BAT1 \ .. \ myBatchFiles \ BAT1 \ f1.bat',它将解析为'C:\ Users \ GntS \ myProject \ bin \ x64 \ Release \ myBatchFiles \ myBatchFiles \ BAT1 \ f1.bat'(注意两个'myBatchFiles') –

回答

0

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

我汇报它在这里希望帮助某人。

2

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

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

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

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

+0

您能否让一些更清楚一些代码? – GntS