I want to open a local HTML file in the default browser.
For example: Default Browser is Mozilla Firefox.
The file to be opened: C:\My Custom Path\New Folder\AFile.htm
Please note the path has spaces. Depending on conditions I want to append an Id at the end of the URL.
Final URL is C:\My Custom Path\New Folder\AFile.htm#12345
If I open the browser manually, and paste the URL "C:\My Custom Path\New Folder\AFile.htm#12345".
It works fine. Unable to find the best way to do this through code.
i think this is better way:
I ended up doing this. I get the default browser, and used the CreateProcess API to launch the browser with my custom URL. Notice, I add the 'file:///' in the beginning and also surround the string with double quotes.
One can also create a process launching CMD.EXE with the following parameters :
Quick and dirty, but it should work OK
Unfortunately you can't do it only with ShellExecute. But there is some hack.
For example you want to open url like this:
C:\Users\User\Desktop\Some sitename with spaces.htm with the anchor #myAnchor
To make ShellExecute open file:
It's Important to use "file:///" in the beginning, but ShellExecute open this page without anchor.
To open with the anchor you can dynamically create html file with content like this:
And open this dynamic file with ShellExecute.
Hope it helps.
ShellExecute/Ex()
won't work directly using"open"
verb with the anchor (#
) in the URL. even if you usefile://
protocol the anchor will be omitted.The best way is to get the path for the default browser, you can use
FindExecutable
, and then execute it and pass the URL as a parameter.EDIT: Looks like the
file:///
URI scheme is important in cases where the URL includes query string parameters (e.gfile.html?param=foo#bar
) or else the?
is escaped to%3F
(tested in Chrome)Here is my implementation that supports all common web browsers and Microsoft Edge (Windows Store App).
It refers to the issues with queries (
?
) and fragments (#
) in the URI and the issue withfile:///
protocol in combination with the Edge browser.(I use it for HTML output of "Flare" software, that's why the "help" in the naming of variables)