[英]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();
}
和引發的異常:
該系統找不到指定的文件。
批處理文件的目錄為:
C:\Users\GntS\myProject\bin\x64\Release\myBatchFiles\BAT1\f1.bat
輸出的.exe
文件位於:
C:\Users\GntS\myProject\bin\x64\Release
我進行了搜索,但結果均無濟於事。 在相對路徑中運行批處理文件的正確方法是什么?
批處理文件將相對於工作目錄(即f1.bat)
但是,您的工作目錄應該是絕對路徑。 無法保證您的應用程序當前使用哪個路徑(可以在.lnk中設置)。 特別是它不是exe路徑。
因此,您應該使用從AppDomain.CurrentDomain.BaseDirectory(或任何其他眾所周知的方法)獲得的exe文件的路徑來構建批處理文件和/或工作目錄的路徑。
最后-使用Path.Combine確定格式正確的路徑。
據JeffRSon`的答案和我的問題解決了如下MaciejLos和KevinGosse評論:
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";
我在這里報告,希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.