How to associate a file extension to the current executable in C#

后端 未结 9 2144
故里飘歌
故里飘歌 2020-11-22 12:01

I\'d like to to associate a file extension to the current executable in C#. This way when the user clicks on the file afterwards in explorer, it\'ll run my executable with t

9条回答
  •  抹茶落季
    2020-11-22 12:58

    There are two cmd tools that have been around since Windows 7 which make it very easy to create simple file associations. They are assoc and ftype. Here's a basic explanation of each command.

    • Assoc - associates a file extension (like '.txt') with a "file type."
    • FType - defines an executable to run when the user opens a given "file type."

    Note that these are cmd tools and not executable files (exe). This means that they can only be run in a cmd window, or by using ShellExecute with "cmd /c assoc." You can learn more about them at the links or by typing "assoc /?" and "ftype /?" at a cmd prompt.

    So to associate an application with a .bob extension, you could open a cmd window (WindowKey+R, type cmd, press enter) and run the following:

    assoc .bob=BobFile
    ftype BobFile=c:\temp\BobView.exe "%1"
    

    This is much simpler than messing with the registry and it is more likely to work in future windows version.

    Wrapping it up, here is a C# function to create a file association:

    public static int setFileAssociation(string[] extensions, string fileType, string openCommandString) {
        int v = execute("cmd", "/c ftype " + fileType + "=" + openCommandString);
        foreach (string ext in extensions) {
            v = execute("cmd", "/c assoc " + ext + "=" + fileType);
            if (v != 0) return v;
        }
        return v;
    }
    public static int execute(string exeFilename, string arguments) {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = true;
        startInfo.FileName = exeFilename;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = arguments;
        try {
            using (Process exeProcess = Process.Start(startInfo)) {
                exeProcess.WaitForExit();
                return exeProcess.ExitCode;
            }
        } catch {
            return 1;
        }
    }
    

提交回复
热议问题