当您使用应用程序打开文件时,该文件的路径将作为第一个命令行参数传递。
在 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
}
}
//...
}
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>
您的命令行参数现在将位于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
}
}
}