Open custom file with own application [duplicate]

淺唱寂寞╮ 提交于 2019-12-31 00:43:05

问题


Possible Duplicate:
How to associate a file extension to the current executable in C#

So, I'm making an application for school (final project).

In this application, I have a Project-class. This can be saved as a custom file, e.g. Test.gpr. (.gpr is the extension).

How can I let windows/my application associate the .gpr file with this application, so that if I doubleclick the .gpr file, my application fires and opens the file (so launches the OpenProject method - This loads the project).

I am NOT asking how to let windows associate a file type with an application, I am asking how to catch this in my code in Visual Studio 2012.

UPDATE: Since my question seems to be not so clear:

atm, I've done nothing, so I can follow whatever is the best solution. All I want is to doubleclick the .gpr, make sure windows knows to open it with my app, and catch the filepath in my application.

Any help is greatly appreciated!


回答1:


When you open a file with an application, the path to that file is passed as the first command line argument.

In C#, this is args[0] of your Main method.

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

    //...
}

WPF

In case your project is an WPF application, in your App.xaml add a Startup event handler:

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

Your command line arguments will now be in e.Args of the Application_Startup event handler:

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


来源:https://stackoverflow.com/questions/13654197/open-custom-file-with-own-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!