好的,所以我正在制作一個程式啟動器,但是我嘗試運行的檔案有一個隨機名稱。這是我的代碼,它可以作業,但是當名稱更改為隨機名稱時,它將停止作業
private void button1_Click(object sender, EventArgs e)
{
Process process = new Process()
{
StartInfo = new ProcessStartInfo(Environment.CurrentDirectory "/Files/330637421.exe")
{
WindowStyle = ProcessWindowStyle.Normal,
WorkingDirectory = Path.GetDirectoryName(Environment.CurrentDirectory "/Files/")
}
};
process.Start();
}
現在它可以作業了,因為我的檔案名為 330637421.exe 但它會拋出一個例外,因為如果它更改了名稱,該檔案將不存在。順便說一句,它是 Files 檔案夾中唯一的 exe 檔案。有沒有辦法運行該檔案夾中的每個 exe 檔案?還保留作業目錄
uj5u.com熱心網友回復:
這是從Directory.GetFiles()以下位置獲取第一個回傳檔案的示例:
String folder = System.IO.Path.Combine(Environment.CurrentDirectory, "Files");
if (System.IO.Directory.Exists(folder))
{
String executable = System.IO.Directory.GetFiles(folder, "*.exe").FirstOrDefault();
if (executable != null)
{
Process process = new Process()
{
StartInfo = new ProcessStartInfo(executable)
{
WindowStyle = ProcessWindowStyle.Normal,
WorkingDirectory = folder
}
};
process.Start();
}
else
{
MessageBox.Show("No .EXE found in the ../Files Folder!");
}
}
else
{
MessageBox.Show("No ../Files Folder Exists!");
}
uj5u.com熱心網友回復:
您可以使用GetFiles方法來獲取檔案。但是如果此路徑中有多個檔案,則必須小心。然后您可以使用模式來獲取特定檔案。
您可以使用檔案中提到的所需多載方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/357983.html
