Rikus Honey
Rikus Honey

Reputation: 558

Get folder path from drag and drop on C# console application .exe

I have written this simple program that when a file gets dragged on the .exe it copies the file's path to the clipboard and exits. The problem is it doesn't seem to work with folders and I would like to add compatibility for folders as well.

Here is the code:

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

Any suggestions? I know the code might not be optimal for what I would like to achieve, but it works, although feel free to leave any comments regarding the improvement of the code.

Upvotes: 0

Views: 1638

Answers (1)

adv12
adv12

Reputation: 8551

For a directory, you can use Directory.Exists. So you could do:

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]))
    {
        ...
    }
}

...or if you want the same handling for both files and directories, combine the two:

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

Upvotes: 2

Related Questions