简体   繁体   中英

C# Winforms application opens from Command Prompt and in debugger, but not from File Explorer

I programmed this C# Winforms app to open when a file is clicked on in the File Explorer (from the "Open with..." command). However, instead of opening, the app simply crashes without an error message. From the Task Manager, the app can be seen running briefly before disappearing.

From a test app, I was able to find out that the File Explorer sends a file path as the first argument. Starting the app from a debugger or from the Command Prompt works (even with a file path as an argument).

Here's the code:

public static void Main(string[] args) {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        MainForm form = new MainForm();

        if (args.Length > 0) {
            if (System.IO.File.Exists(args[0])) {
                form.OpenFile_(args[0]);
            }
        }

        try {
            Application.Run(form);
        } catch (Exception e) {
            form = new MainForm();
            form.SetStatus("Something went wrong opening the file.");
            Application.Run(form);
        }
    }

Even with the try/catch block, the app fails to start from the File Explorer. It works without any problems from the Command Prompt or in a debugger.

It's simple, really:

Instead of:

string SettingsFilePath = "settings.txt";

Use:

string SettingsFilePath = Application.StartupPath + "\\settings.txt";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM