用自己的应用打开自定义文件

Val*_*uyt 4 c# visual-studio-2012

可能重复:
如何将文件扩展名与C#中的当前可执行文件关联

所以,我正在申请学校(最终项目).

在这个应用程序中,我有一个Project类.这可以保存为自定义文件,例如Test.gpr.(.gpr是扩展名).

我怎样才能让Windows /我的应用程序.gpr后的文件与此应用程序相关联,因此,如果我双击了.gpr后的文件,我的应用程序火灾和打开文件(这样启动OpenProject方法 - 这会将项目).

不是问如何让Windows将文件类型与应用程序关联,我问如何在我的Visual Studio 2012代码中捕获它.

更新: 由于我的问题似乎不太清楚:

atm,我什么也没做,所以我可以遵循最好的解决方案.我想要的是双击.gpr,确保Windows知道用我的应用程序打开它,并在我的应用程序中捕获文件路径.

任何帮助是极大的赞赏!

nee*_*eKo 10

使用应用程序打开文件时,该文件的路径将作为第一个命令行参数传递.

在C#中,这是args[0]你的Main方法.

static void Main(string[] args)
{
    if(args.Length == 1) //make sure an argument is passed
    {
        FileInfo file = new FileInfo(args[0]);
        if(file.Exists) //make sure it's actually a file
        {
           //Do whatever
        }
    }

    //...
}
Run Code Online (Sandbox Code Playgroud)

WPF

如果您的项目是WPF应用程序,请在App.xaml添加Startup事件处理程序中:

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml"
             Startup="Application_Startup"> <!--this line added-->
    <Application.Resources>

    </Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)

你的命令行参数现在将是e.Args对的Application_Startup事件处理程序:

private void Application_Startup(object sender, StartupEventArgs e)
{
    if(e.Args.Length == 1) //make sure an argument is passed
    {
        FileInfo file = new FileInfo(e.Args[0]);
        if(file.Exists) //make sure it's actually a file
        {
           //Do whatever
        }
    }
}
Run Code Online (Sandbox Code Playgroud)