[英]How can I programmatically check file that a file association exists before attempting to Process.Start() it?
[英]Check if the process exists before process.start();
我做了一個執行可執行文件(.exe)的小程序,但是當您寫下不存在的文件時出現錯誤,找不到特定於文件的文件。
所以我想知道是否有一種方法可以在運行該進程之前先檢查該進程是否存在,如果不存在,則可以顯示一個消息框。
這是我的代碼
private void btn_Start_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
Process process = new Process();
if (!textBox1.Text.Contains(".exe"))
{
process.StartInfo.FileName = text + ".exe";
}
else
{
process.StartInfo.FileName = text;
}
process.Start();
}
在啟動過程之前,請檢查文件是否存在:
var processFileName = !textBox1.Text.Contains(".exe")
? text + ".exe"
: text;
if (File.Exists(processFileName))
{
Process process = new Process();
process.Start(processFileName);
}
請嘗試以下代碼:->(使用“ File.Exists”命令之前,您必須添加#using System.IO;)
button1_Click(object sender, EventArgs )
{
string exepath = "C:\\example\\example.xlsx";
if(File.Exists(exepath))
{
Process.Start(exepath);
}
else
{
MessageBox.Show("File not found!");
}
}
希望它能正常工作!
您可以在路徑中輸入字符串,然后在其他字符串中輸入文件名,然后甚至可以檢查“文件夾”,如果該文件夾存在,請檢查該文件! 您也可以使用textbox1作為文件名,但是必須添加路徑,除非它將在程序目錄中搜索。(bin / debug)如果我輸入錯誤,請原諒,我現在正在學習c#! 祝你有美好的一天!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.