Search code examples
c#.netwindowswinformsopen-with

When a file is "opened with" a winforms application how do I get the application to use that file's directory?


I am able to set my .mdb files to "open with" my winforms application, but that only opens the winforms application without loading the file. Is there any event that is triggered upon opening the application through a file that will allow me to grab the filename/file-directory to load it into my app?

Update:

apparently this can be done for "Windows Store Apps": File "Open with" my Windows Store App

But it seems as though my winforms project lacks a package.appxmanifest to edit these settings from, nor does my project have access to the Windows.ApplicationModel.Activation.FileActivatedEventArgs and Windows.UI.Xaml.Application.OnFileActivated APIs needed for this method.


Solution

  • When you double-click an mdb file, your application will be executed with mdb file argument. Similar to calling your app from command line:

    > your-app.exe "test.mdb"
    

    You should use the args in the Main method.

    class Program
    {
        static void Main(string[] args)
        {
            // check that user provided a file to open
            if (args != null && args.Length > 0)
            {
                var mdbFilePath = args[0];
                // TODO: read the file
            }
    
            // ...