简体   繁体   中英

Read serialized file associated with a program upon open

I have finished my program, serialized it for saving and created a fileopen system to open a file saved from my application. I have even created a file association with innosetup on the registry, which works perfectly fine.

All I want to achieve now is, whenever a user double click on a saved file from the program, the program should read and deserialize it.

For example, when you double click or open a .docx or .doc file, Microsoft Word is opened and the file is read and opened. Presently my program will open, but I don't know how to detect when it is opened from a file so I can start deserialization.

Note: Deserializing itself is not the problem, it's detecting whether or not I should do so.

When you start a program by double clicking on an associated file, the filename is passed in as a command line argument. You specify where this argument will occur in your file extension association setup.

If you set up your association as:

program.exe %1

Double clicking your file will result in:

program.exe C:\\Folder\\File.ext

This can be accessed using Environment.GetCommandLineArgs() or from your Main(string[] args) method:

static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            // Get the argument
            string fileLocation = args[0];

            // Load and deserialize
            // Do the do
        }
    }

Here is an MSDN article on command line arguments .

Thanks @Macropus, you actually didn't tell me what I did not know, you pointed a light to my error. This happens when I was setting the registry values on innosetup

instead of {app}\\program.exe %1 on innosetup I wrote, "{app}\\program.exe" "%1"

which neglected the path to the file that opened the program.

So when I query Environment.GetCommandLineArgs();

only the path to the program.exe is returned but now, both the program.exe and the path to the file to called the program is returned which is accessed from Environment.GetCommandLineArgs()[1]

To make this work when I open the file from a shortcut or the program.exe itself, I did

var comArgs = Environment.GetCommandLineArgs();
if (comArgs.Length > 1)
{
    // Then I can deserialize here.
}

Working now and thank you all.

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