2017-07-08 65 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