我正在使用以下方法打开文件:
Process.Start();
如果具有某些扩展名的特定文件与 Windows 中不再存在的程序相关联,则会抛出 Win32Exception。现在我可以简单地做
try{
Process.start();
} catch( Exception ex){
// Error handling code
}
但是,应我雇主的要求,我被要求不要这样做。相反,我想通过检查关联的程序/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
}
}
}
关于c# - 如何使用 C# 检查与文件扩展名关联的程序是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15980353/