从C#console application.exe上的拖放获取文件夹路径
我编写了一个简单的程序,当文件在.exe上被拖动时,它会将文件的路径复制到剪贴板并退出。问题是它似乎不适用于文件夹,我也想为文件夹添加兼容性 代码如下:从C#console application.exe上的拖放获取文件夹路径,c#,console,C#,Console,我编写了一个简单的程序,当文件在.exe上被拖动时,它会将文件的路径复制到剪贴板并退出。问题是它似乎不适用于文件夹,我也想为文件夹添加兼容性 代码如下: using System; using System.IO; using System.Windows.Forms; namespace GetFilePath { class Program { [STAThread] static void Main(string[] args)
using System;
using System.IO;
using System.Windows.Forms;
namespace GetFilePath
{
class Program
{
[STAThread]
static void Main(string[] args)
{
Console.Title = "Getting path...";
if (args.Length > 0 && File.Exists(args[0]))
{
string path;
path = args[0];
Console.WriteLine(path);
Clipboard.Clear();
Clipboard.SetText(path);
MessageBox.Show("Path copied to clipboard", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
有什么建议吗?我知道代码对于我想要实现的目标可能不是最优的,但是它是有效的,尽管您可以对代码的改进留下任何意见。对于目录,您可以使用
directory.Exists
。所以你可以做:
if (args.Length > 0)
{
if (File.Exists(args[0]))
{
string path;
path = args[0];
Console.WriteLine(path);
Clipboard.Clear();
Clipboard.SetText(path);
MessageBox.Show("Path copied to clipboard", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (Directory.Exists(args[0]))
{
...
}
}
…或者,如果您希望对文件和目录进行相同的处理,请将两者结合起来:
if (args.Length > 0 && (File.Exists(args[0]) || Directory.Exists(args[0])))
{
string path;
path = args[0];
Console.WriteLine(path);
Clipboard.Clear();
Clipboard.SetText(path);
MessageBox.Show("Path copied to clipboard", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
}