How do I launch files in C#

85,064

Solution 1

Use:

System.Diagnostics.Process.Start(filePath);

It will use the default program that would be opened as if you just clicked on it. Admittedly it doesn't let you choose the program that will run... but assuming that you want to mimic the behaviour that would be used if the user were to double-click on the file, this should work just fine.

Solution 2

It really sounds like you're looking more for this:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = "<whatever>";
proc.Start();

Solution 3

Assuming that you just want to launch files which already have some associated applications (eg: *.txt is associated with notepad), Use System.Diagnostics.Process.

e.g. :

 using System.Diagnostics;
    Process p = new Process();
    ProcessStartInfo pi = new ProcessStartInfo();
    pi.UseShellExecute = true;
    pi.FileName = @"MY_FILE_WITH_FULL_PATH.jpg";
    p.StartInfo = pi;

    try
    {
        p.Start();
    }
    catch (Exception Ex)
    {
        //MessageBox.Show(Ex.Message);
    }

Note: In my PC, the pic opens in Windows Picture & Fax Viewer since that is the default application for *.jpg files.

Solution 4

For me at least, using DotNet 5+ / Dotnet Core the System.Diagnostics.Process.Start doesn't work (on Windows 10 or 11). So I used the ShellExecute API instead.

Call the below code by using

ShellExecute("filename");

eg. ShellExecute("c:\temp\test.txt");

C# code for the method:

using System.Runtime.InteropServices;     
[DllImport("Shell32.dll")]
        private static extern int ShellExecuteA(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirecotry, int nShowCmd);

    public static int ShellExecute(string filename, string parameters = "", string workingFolder = "", string verb = "open", int windowOption = 1)
    {
        //calls Windows ShellExecute API
        //for verbs see https://docs.microsoft.com/en-us/windows/win32/shell/launch (open/edit/runas...)
        //for windowOptions see https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow (show/hide/maximize etc)

        IntPtr parentWindow = IntPtr.Zero;

        try
        {
            int pid = ShellExecuteA(parentWindow, verb, filename, parameters, workingFolder, windowOption);
            return pid;
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex.Message);
            return 0;
        }
        
    }
Share:
85,064
Admin
Author by

Admin

Updated on February 03, 2022

Comments

  • Admin
    Admin over 2 years

    -Edit- I feel like an idiot. I had a feeling something like the answer below would work but didn't see any google results similar to the answers below. So when I saw this complex code I thought it had to be this way.

    I searched and found this Windows: List and Launch applications associated with an extension however it didn't answer my question. With tweaks below, I came up with the below. However, it gets stuck on image files. Txt files run fine

    I will update this code soon to account for app paths with spaces however I don't understand why image files don't launch.

    static void launchFile(string fn)
    {
        //majority was taken from
        //https://stackoverflow.com/questions/24954/windows-list-and-launch-applications-associated-with-an-extension
        const string extPathTemplate = @"HKEY_CLASSES_ROOT\{0}";
        const string cmdPathTemplate = @"HKEY_CLASSES_ROOT\{0}\shell\open\command";
    
        string ext = Path.GetExtension(fn);
    
        var extPath = string.Format(extPathTemplate, ext);
    
        var docName = Registry.GetValue(extPath, string.Empty, string.Empty) as string;
        if (!string.IsNullOrEmpty(docName))
        {
            // 2. Find out which command is associated with our extension
            var associatedCmdPath = string.Format(cmdPathTemplate, docName);
            var associatedCmd = Registry.GetValue(associatedCmdPath, string.Empty, string.Empty) as string;
    
            if (!string.IsNullOrEmpty(associatedCmd))
            {
                //Console.WriteLine("\"{0}\" command is associated with {1} extension", associatedCmd, ext);
                var p = new Process();
                p.StartInfo.FileName = associatedCmd.Split(' ')[0];
                string s2 = associatedCmd.Substring(p.StartInfo.FileName.Length + 1);
                s2 = s2.Replace("%1", string.Format("\"{0}\"", fn));
                p.StartInfo.Arguments = s2;//string.Format("\"{0}\"", fn);
                p.Start();
            }
        }
    }
    
  • Matthew Iselin
    Matthew Iselin over 14 years
    Aww, you just beat me :)
  • Awesome_girl
    Awesome_girl about 9 years
    how about you wanted to open it with a specific program, I want to open it with "Windows PowerShell ISE"
  • Saleem Kalro
    Saleem Kalro almost 7 years
    great..Working Well
  • Hamid Z
    Hamid Z almost 3 years
    on windows 10 and .net 5 i got this error: "The specified executable is not a valid application for this OS platform"
  • Nate Cook3
    Nate Cook3 over 2 years
    @HamidZ the program associated with that file does not exist or is invalid.