如何检查C#WPF中是否安装了邮件客户端

时间:2018-09-18 11:42:51

标签: c# wpf email

我有WPF桌面应用程序,其中包含邮件链接。如果单击链接,将打开默认的邮件客户端。但是,如果计算机没有配置的电子邮件客户端,则该程序将崩溃并发生严重异常

System.NullReferenceException: The object reference does not point to an instance of the object.
at Nvx.ReDoc.DesktopUi.View.Tray.Sections.About.AboutWindow.OnRequestNavigate(Object sender, RequestNavigateEventArgs e) 



  <Other:ReDocHyperlinkLite NavigateUri="mailto:mail@mail.com?subject=sampleText" RequestNavigate="OnRequestNavigate">
<Run Text="mail@mail.com"/></Other:ReDocHyperlinkLite>

OnRequestNavigate实现是

private void OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
            e.Handled = true;
        }

如何检查计算机上是否已安装邮件客户端并捕获异常?

1 个答案:

答案 0 :(得分:1)

您可以检查是否已注册一个应用程序来处理mailto URI方案(并另外检查给定的应用程序是否确实存在):

private bool IsSchemeRegistered(string scheme)
{
    using (var schemeKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(scheme))
    {
        if (schemeKey == null)
            return false;

        if (schemeKey.GetValue("") == null || !schemeKey.GetValue("").ToString().StartsWith("URL:"))
            return false;

        using (var shellKey = schemeKey.OpenSubKey("shell"))
        {
            if (shellKey == null)
                return false;

            using (var openKey = shellKey.OpenSubKey("open"))
            {
                if (openKey == null)
                    return false;

                using (var commandKey = openKey.OpenSubKey("command"))
                {
                    if (commandKey == null)
                        return false;

                    var command = commandKey.GetValue("") as string;
                    if (string.IsNullOrEmpty(command) || !File.Exists(command.Split(new[] { '"' }, StringSplitOptions.RemoveEmptyEntries).First()))
                        return false;

                }
            }
        }
    }
    return true;
}

此方法的调用方式如下:

if ( !IsSchemeRegistered("mailto") )
{  
     MessageBox.Show("No mail client installed/configured");
}
else
{
    //...
}