【问题标题】:Catch opening of file if there's no program to open it如果没有程序可以打开文件,则捕获文件的打开
【发布时间】:2013-05-13 02:29:13
【问题描述】:

我的代码

var info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
info.WindowStyle = ProcessWindowStyle.Maximized;
var p = Process.Start(info);

它将打开一个文件(.pdf,但以后可能是另一种类型的文件) 在某些情况下,没有安装程序来打开它,所以它会显示 Windows 消息

Windows 无法打开此文件

并让我搜索一些程序来打开它。

我怎样才能避免这种情况? 我想显示另一条消息。在try/catch 中它不会抛出任何异常,所以它不起作用。

我试过了,if is only .pdf 来检测是否有任何程序安装了这个

var key = Registry.ClassesRoot.OpenSubKey(".pdf");
if(key != null)
//  Not installed!

但它不起作用。我得到了一个密钥,但我已经卸载了 Foxit 阅读器(我还使用 CCleaner 删除了冲突密钥,但仍然有 .pdf 密钥)

请帮忙

【问题讨论】:

标签: c# .net winforms pdf registry


【解决方案1】:

您可以使用FindExecutable() API,要检查的文件必须实际存在:

    [System.Runtime.InteropServices.DllImport("shell32.dll")]
    static extern IntPtr FindExecutable(string lpFile, string lpDirectory, StringBuilder lpResult);

    private void Button1_Click(System.Object sender, System.EventArgs e)
    {
        string path = @"C:\Users\Mike\Documents\SomeFile.xyz";
        string EXE = GetAssociatedExecutable(path);
        if (!string.IsNullOrEmpty(EXE))
        {
            MessageBox.Show(EXE, "Associated Executable");
        }
        else
        {
            MessageBox.Show("No Asssociated Executable for: " + path);
        }
    }

    private string GetAssociatedExecutable(string filename)
    {
        const int MAX_PATH = 260;
        if (System.IO.File.Exists(filename))
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(MAX_PATH);
            FindExecutable(filename, null, sb);
            if (sb.Length > 0)
            {
                return sb.ToString();
            }
        }
        return "";
    }

【讨论】:

    猜你喜欢
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多