Trilinisty Gaming
Trilinisty Gaming

Reputation: 13

How do I detect if the user has opened my C# forms app with a file

I am trying to find a way to see if my program was opened with a file (e.g dragging a txt over an EXE to open with), how would I see if the user has opened my EXE with a file, and how do I get the filename of said file.

I tried looking through al the C# Form load events but couldn't find anything that matched.

Upvotes: 1

Views: 75

Answers (1)

Drew McGowen
Drew McGowen

Reputation: 11706

When you drag-n-drop a file on an exe, Windows runs the exe with the file's path as a command-line argument. In your Main function, you can add a string[] args parameter to access the command-line arguments; you can then check if args.Length > 0, and use args[0] as your file path.

Example:

static void Main(string[] args)
{
    if (args.Length > 0)
    {
        string path = args[0];
        // use path here
    }
    else
    {
        // exe was run by itself; no path was given
    }
    ...
}

Upvotes: 2

Related Questions