This question already has answers here:
Closed 5 years ago.
Just like when you make a reference in windows, to open a .txt file, it may open NotePad.exe and or Word.exe, while loading the text from the file into the editor. How can I do this with my Desktop Application. I am having a custom file type for it with extension .mmi. I want it so that when the user double click this file type it will not only open my application, but load the data within it into the appropriate areas of my application. I understand how to set the custom file type for my application settings, but where I am lost is how to get the file info that trigger opening my application so I can get the data from it.
For example. If I open a .html, and choose to use notepad.exe, the html is now loaded in the newly opened text editor.
This is for a From Application, not a console application that starts off with main having args, incase that helps or changes anything.
Example below:
public partial class FormDashboard : Form
{
public FormDashboard()
{
InitializeComponent();
}
private void FormDashboard_Load(object sender, EventArgs e)
{
//I want to get what file trigger the app to open here, and apply the data accordingly throurght the forms application.
}
The answer to your question is no different for a WinForms app and a console app.
The path of the .mmi
file that triggered your app will be args[0]
in your app's Main
method (assuming the signature Main(string[] args)
).
So knowing what .mmi
file was double-clicked to trigger your app will essentially come for free - after you have told Windows to open .mmi
files with your app.
Here is an example - where I just used a text file Test.mmi
and a simple console app ConsoleApplication1
for a PoC:
/*
* Program.cs
*/
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
// Open and display the text in the double-clicked .mmi file.
Console.WriteLine(File.ReadAllText(args[0]));
}
// Pause for 5 seconds to see the double-clicked file's text.
Thread.Sleep(5000);
}
}
}
After telling Windows to open .mmi
files with ConsoleApplication1.exe
, ConsoleApplication1.exe
displays the text in Test.mmi
(Whatever....
) when I double-click it:
The only thing that will differ from the PoC I have offered is whatever you need do with the file path that comes in as args[0]
.
The file name will be passed to your application as the first command line parameter. You can get to it using this code:
static void Main(string[] args)
{
if (args.Length > 0)
{
//do stuff with args[0]
}
}
Or, if you are in WPF, handle the Application.Startup
event and get the parameter from e.Args
.
I think all you need is to read command lines arguments. The file to be opened should be your unique argument.
class MyClass
{
static void Main(string[] args)
{
// args[0] = file name to be opened by your application