使用自己的应用程序打开自定义文件
可能重复:
如何关联文件扩展名到C#中的当前可执行文件
所以,我正在申请学校(最终项目).
So, I'm making an application for school (final project).
在此应用程序中,我有一个 Project
类.可以将其另存为自定义文件,例如测试. gpr .(.gpr是扩展名).
In this application, I have a Project
-class.
This can be saved as a custom file, e.g. Test.gpr.
(.gpr is the extension).
如何让Windows/我的应用程序将.gpr文件与此应用程序相关联,因此,如果我双击.gpr文件,则我的应用程序将启动并打开该文件(因此启动OpenProject方法-这将加载项目).
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).
我不询问如何让Windows将文件类型与应用程序相关联,我询问如何在Visual Studio 2012的代码中捕获该问题.
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,我什么也没做,所以我可以遵循最佳解决方案.我想要的就是双击.gpr,确保Windows知道可以使用我的应用程序打开它,并在我的应用程序中捕获文件路径.
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.
任何帮助将不胜感激!
使用应用程序打开文件时,该文件的路径将作为第一个命令行参数传递.
When you open a file with an application, the path to that file is passed as the first command line argument.
在C#中,这是 Main
方法的 args [0]
.
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
如果您的项目是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>
您的命令行参数现在将位于 Application_Startup
事件处理程序的 e.Args
中:
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
}
}
}