获取用我的应用程序打开的文件的路径+文件名

我是c#的业余爱好者,我一直无法找到答案。 也许我不知道正确使用的术语。

当video文件被拖到我的exe应用程序上时,我希望应用程序知道它是用文件启动的,并且能够知道该文件的路径和文件名。 这样,用户不必使用文件>打开菜单。

希望有道理。 谢谢

您可以检查用于启动应用程序的命令行参数。 如果通过在.exe文件上删除文件来启动应用程序,则会有一个命令行参数和文件路径。

string[] args = System.Environment.GetCommandLineArgs(); if(args.Length == 1) { // make sure it is a file and not some other command-line argument if(System.IO.File.Exists(args[0]) { string filePath = args[0]; // open file etc. } } 

正如您的问题标题所述,您需要路径和文件名。 您可以使用以下方式获取文件名:

 System.IO.Path.GetFileName(filePath); // returns file.ext 

将文件拖入C#应用程序时,它将作为该应用程序的命令行参数。 与控制台应用程序一样,您可以在Program类的Main方法上捕获它。

我将使用Windows Forms应用程序解释它。

在解决方案上打开您的Program类。 你的程序类应该是这样的。

 static class Program { ///  /// The main entry point for the application. ///  [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } 

默认情况下,在创建Windows窗体应用程序时,它们不会处理命令行参数。 您必须对Main方法的签名进行微小更改,以便它可以接收参数:

 static class Program { ///  /// The main entry point for the application. ///  [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } 

现在您可以处理传递给应用程序的文件名参数。 默认情况下,Windows会将文件名作为第一个参数。 做这样的事情:

  static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Before Application.Run method, treat the argument passed. // I created an overload of the constructor of my Form1, so // it can receive the File Name and load the file on some TextBox. string fileName = null; if (args != null && args.Length > 0) fileName = args[0]; Application.Run(new Form1(fileName)); } 

如果你想知道我的Form1的构造函数重载,这里是。 希望能帮助到你!

 public partial class Form1 : Form { public Form1() { InitializeComponent(); } public Form1(string fileName) : this() { if (fileName == null) return; if (!File.Exists(fileName)) { MessageBox.Show("Invalid file name."); return; } textBox1.Text = File.ReadAllText(fileName); } } 

您需要应用程序的命令行参数。 在资源管理器中删除应用程序上的文件时,资源管理器会打开包含您放在其上的文件的应用程序。 您可以根据需要选择任意数量的文件,将它们放在应用程序上并使用这行代码, files将是这些命令行参数的数组。

 string[] files = Environment.GetCommandLineArgs();