允许自定义文件双击并打开我的应用程序,同时加载它的数据

就像在Windows中进行引用一样,要打开.txt文件,它可能会打开NotePad.exe和/或Word.exe,同时将文件中的文本加载到编辑器中。 如何使用我的桌面应用程序执行此操作。 我有一个自定义文件类型,扩展名为.mmi。 我想要它,以便当用户双击此文件类型时,它不仅会打开我的应用程序,而是将其中的数据加载到我的应用程序的相应区域。 我理解如何为我的应用程序设置设置自定义文件类型,但我丢失的地方是如何获取触发打开我的应用程序的文件信息,以便我可以从中获取数据。

例如。 如果我打开.html,并选择使用notepad.exe,则html现在会加载到新打开的文本编辑器中。

这适用于From应用程序,而不是以main为args的控制台应用程序,可以帮助或更改任何内容。

示例如下:

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. } 

对于WinForms应用程序和控制台应用程序,您的问题的答案没有什么不同。

触发应用程序的.mmi文件的路径将是应用程序的Main方法中的args[0] (假设签名为Main(string[] args) )。

因此,在您告诉Windows使用您的应用程序打开.mmi文件之后,知道双击什么.mmi文件来触发您的应用程序基本上是免费的。

这是一个例子 – 我刚刚使用文本文件Test.mmi和一个简单的控制台应用程序ConsoleApplication1用于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); } } } 

在告诉Windows使用ConsoleApplication1.exe打开.mmi文件后, ConsoleApplication1.exe在我双击时显示Test.mmiWhatever.... )中的文本:

ConsoleApplication1.exe输出

唯一不同于我提供的PoC的是你需要做的任何文件路径作为args[0]

文件名将作为第一个命令行参数传递给您的应用程序。 您可以使用以下代码访问它:

 static void Main(string[] args) { if (args.Length > 0) { //do stuff with args[0] } } 

或者,如果您在WPF中,请处理Application.Startup事件并从e.Args获取参数。

我认为你需要的只是阅读命令行参数。 要打开的文件应该是您唯一的参数。

  class MyClass { static void Main(string[] args) { // args[0] = file name to be opened by your application