0
using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Diagnostics.Process.Start(@"C:\Users\MyUsername\Desktop\TextFile.txt");
        }
    }
}

ERROR GIVEN: The specified executable is not a valid application for this OS platform.'

Any ideas?

Toto
  • 89,455
  • 62
  • 89
  • 125
  • 3
    You need a `ProcessStartInfo` object that specifies that you want to use the _Shell_ to start things up. The shell understands file associations (like "use Notepad to start `.txt` files). Otherwise it will try to start your file as an `EXE`, which it is not – Flydog57 Aug 12 '21 at 23:19
  • 1
    Text files (`TextFile.txt` or any other `txt` file) are not executable. You have to use the shell's file associations to tell it to use the default application to *open* the text file. – Ken White Aug 12 '21 at 23:22
  • In other words, try this string instead `@"notepad.exe C:\Users\MyUsername\Desktop\TextFile.txt"` – h0r53 Aug 12 '21 at 23:32
  • 2
    @h0r53: That's incorrect. You should do as Flydog57 suggested and use `ProcessStartInfo`, and let the user's default text editor (which may not be Notepad) open the file. – Ken White Aug 13 '21 at 00:00
  • 2
    That would work in .Net Framework, where `UseShellExecute = true` by default, the opposite in .Net Core / .Net 5+, so you need to set it explicitly to `true` (in any case, more *migration friendly*). – Jimi Aug 13 '21 at 00:11

1 Answers1

1

To launch a file with the default application, use ProcessStartInfo and set UseShellExecute to true. For example:

Process.Start(new ProcessStartInfo("file.txt") { UseShellExecute = true });

For further reading, see When do we need to set ProcessStartInfo.UseShellExecute to True?.

UseShellExecute is defaulted to true for the full .Net Framework, so the above is equivalent to:

// NOTE: Only for .Net Framework - will not work on .Net Core / .Net 5+
Process.Start("file.txt");
Mitch
  • 21,223
  • 6
  • 63
  • 86