通过拖放C#控制台应用程序获取文件夹路径.exe

时间:2015-12-18 17:29:58

标签: c# console

我编写了这个简单的程序,当文件被拖到.exe上时,它会将文件的路径复制到剪贴板并退出。问题是它似乎不适用于文件夹,我也希望为文件夹添加兼容性。

以下是代码:

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

有什么建议吗?我知道代码可能不是我希望实现的最佳代码,但它可以工作,但可以随意留下有关代码改进的任何评论。

1 个答案:

答案 0 :(得分:2)

对于目录,您可以使用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);
}