2

I am trying to use ShellExecute to open a .txt file in the default browser.

I am currently using

ShellExecute(0, L"open", L"http://E:/path/to/file.txt", 0, 0, 1);

This correctly creates a new window in the browser but tries to open

E/path/to/file.txt (without the ":")

and then can not find the associated file. The file location is definitely correct as manually adding the ":" back in the browser opens the file as desired.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Alex
  • 33
  • 1
  • 5
  • Why do you want to display a `.txt` file in the default browser ? Create a html file – Marged Jan 05 '16 at 14:46
  • 3
    `http://` is ONLY for HTTP URLs. Use `file://` instead, and [mind the rules](https://blogs.msdn.microsoft.com/ie/2006/12/06/file-uris-in-windows/). – andlabs Jan 05 '16 at 14:49
  • Even if this _hack_ is working: have you tried what happens when your default browser is Chrome or Firefox ? Or a different version of the browser you are working with ? – Marged Jan 05 '16 at 14:51

2 Answers2

1

Option 1

Use AssocQueryString or IQueryAssocations to figure out the default browser, then launch that browser with your text file on the command line.

Option 2

Create a temporary .html file with a <meta> tag that redirects to a file:// URL that loads the text file. Then ShellExecute with your temporary .html file. Since the temp file is of type .html, it should load the user's default browser. The redirect will then cause the browser to load the text file.

The trick is figuring out when to clean up your temporary file. ShellExecute doesn't make it easy to get a handle to the launched process (and, in reality, the process you launch may just launch another process), so you don't have an easy way to know when the browser is done with your temporary file. You might just keep track of the temporary files you create and try to delete them when your application closes.

Adrian McCarthy
  • 45,555
  • 16
  • 123
  • 175
-2

ShellExecute will open a txt file inside the default text viewer, which isn't a browser I suppose. To open inside a browser, explicitely run the browser and give the file as argument. For example:

ShellExecute(
    0,
    L"open",
    L"C:\\Program Files\\Internet Explorer\\iexplore",
    L"E:\\path\\to\\file.txt",
    0,
    1
);
mikedu95
  • 1,725
  • 2
  • 12
  • 24
  • It's not a good idea to assume which browser to launch or where it is installed. – Adrian McCarthy Jan 05 '16 at 18:48
  • So you think that if I have to write a little program to do a very specific task on my very specific computer for example, I shouldn't make assumptions on the software installed and on their locations ? – mikedu95 Jan 05 '16 at 18:56
  • You can do what you like on your own machine, of course. But many developers use StackOverflow for advice on how to construct software used by others, so it's more valuable if the answers here deal in what's safe to do on other people's machines. – Adrian McCarthy Jan 05 '16 at 22:54