![](/img/trans.png)
[英]Is there a way to check wheather the c# program was opened by a file with associated extension?
[英]How do I use C# to check if program associated with file extension is valid?
我正在使用以下方法打開文件:
Process.Start();
如果具有某些擴展名的特定文件與Windows中不再存在的程序相關聯,則將引發Win32Exception。 現在我可以簡單地做
try{
Process.start();
} catch( Exception ex){
// Error handling code
}
但是,應我雇主的要求,我被要求不要這樣做。 相反,我想通過檢查是否存在關聯的program / path_to_program來解決這個問題,如果不存在,則彈出一個窗口,告訴用戶選擇一個程序來運行文件。
謝謝
創建兩個表單並使用如下代碼:
內部主要形式:
public void SelectProgram(string ext)
{
IEnumerable<string> programList = RecommendedPrograms(ext);
if (programList.Count() > 0)
{
// open a new form to show the program in the list (to user select one of them)
frmSelectProgram frmSP = new frmSelectProgram(programList);
frmSP.ShowDialog();
}
else
{
// show an Open Dialog to the user to select a program
}
}
並使用如下所示的方法來查找與女巫程序關聯的文件(擴展名):(此方法由@LarsTech編寫 ,我更改了其中的幾行。)
using Microsoft.Win32;
public IEnumerable<string> RecommendedPrograms(string ext)
{
List<string> progs = new List<string>();
string baseKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\." + ext;
using (RegistryKey rk = Registry.CurrentUser.OpenSubKey(baseKey + @"\OpenWithList"))
{
if (rk != null)
{
string mruList = (string)rk.GetValue("MRUList");
if (mruList != null)
{
foreach (char c in mruList.ToString())
if(rk.GetValue(c.ToString())!=null)
progs.Add(rk.GetValue(c.ToString()).ToString());
}
}
}
using (RegistryKey rk = Registry.CurrentUser.OpenSubKey(baseKey + @"\OpenWithProgids"))
{
if (rk != null)
{
foreach (string item in rk.GetValueNames())
progs.Add(item);
}
//TO DO: Convert ProgID to ProgramName, etc.
}
return progs;
}
在frmSelectProgram里面的形式:
public partial class frmSelectProgram : Form
{
private IEnumerable<string> _programList;
public frmSelectProgram(IEnumerable<string> programList)
{
InitializeComponent();
_programList = programList;
}
private void frmSelectProgram_Load(object sender, EventArgs e)
{
foreach (string pro in _programList)
{
// MessageBox.Show(pro);
// for example fill a list box
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.