65.9K
CodeProject is changing. Read more.
Home

Opening a File Specifically in the Default Browser

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Jan 9, 2019

CPOL

1 min read

viewsIcon

10346

How to open a file specifically in the default browser, instead of the default app for the file type

Introduction

Recently, LocalCast has stopped working on my Android devices - and that's a pain, because I no longer have a DVD player hooked to my TV (in fact, the only DVD player in the house is inside my PC) and all my videos are now stored on my RAID 5 NAS box. When LocalCast stops working, I can't easily watch videos, which understandably upsets Herself.

Background

Chrome supports direct casting of webpages to a suitable device (such as Chromecast) so all I have to do is open the file in Chrome, cast it, and make it full page. It's a little clumsy, as the video controls are very basic, but it works. All I needed to do was automate the process of loading a non-page based file into Chrome.

And that's easy: change the file system based path to a Uri and paste that into the address bar. Chrome opens the file, and off you go.

But ... that's complicated for Herself, so I wrote a quick program (that runs on my Win10 tablet, the WookieTab) that shows what videos are available, and shows them. She can learn to cast it ... I hope.

But this works for any file type, not just videos.

Using the Code

First off, we need to get the path to the default browser (as it may not be Chrome) - that's in the Registry, under HTTP associations:

/// <summary>
/// Returns the path to the current default browser
/// </summary>
/// <returns></returns>
private static string GetPathToDefaultBrowser()
    {
    const string currentUserSubKey = 
    @"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice";
    using (RegistryKey userChoiceKey = Registry.CurrentUser.OpenSubKey(currentUserSubKey, false))
        {
        string progId = (userChoiceKey.GetValue("ProgId").ToString());
        using (RegistryKey kp = 
               Registry.ClassesRoot.OpenSubKey(progId + @"\shell\open\command", false))
            {
            // Get default value and convert to EXE path.
            // It's stored as:
            //    "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -- "%1"
            // So we want the first quoted string only
            string rawValue = (string) kp.GetValue("");
            Regex reg = new Regex("(?<=\").*?(?=\")");
            Match m = reg.Match(rawValue);
            return m.Success ? m.Value : "";
            }
        }
    }

Then generate a Uri from the file system path:

Uri uri = new System.Uri(filePath);
string converted = uri.AbsoluteUri;

And finally, open the file:

string browserPath = GetPathToDefaultBrowser(); 
Process.Start(browserPath, converted);

History

  • 2019-01-09: First version
  • 2019-01-09: Tidier code in GetPathToDefaultBrowser method