paparazzo
paparazzo

Reputation: 45096

WindowsExplorer Drop Get Files and Files From Folders

From what I can tell there is not way of telling if the drop was a file or a folder.

if (fi.Extension == "") is not sufficient as that matches a directory and also a file with no extension.

The only way I found was to .GetFiles() and handle the exception.

Is there a better way?

    private void ListView0_DragDrop(object sender, DragEventArgs e)
    {
        // Can only drop files, so check
        if (!e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            return;
        }

        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
        FileInfo fileInfo;

        DirectoryInfo dirInfo;
        foreach (string str in files)
        {
            dirInfo = new DirectoryInfo(str);  
            try 
            {
                foreach(FileInfo fi in dirInfo.GetFiles())
                {
                    Debug.WriteLine("File in dir " + fi.Name);
                }
            }
            catch
            {
                fileInfo = new FileInfo(str);
                Debug.WriteLine("File " + str);
            }
        }

Upvotes: 0

Views: 79

Answers (1)

davisoa
davisoa

Reputation: 5439

I would use Directory.Exists and File.Exists before adding a try catch - although you may need the try anyway due to security on the files / directories (both of these Exists methods can throw FileIOException.

DirectoryInfo dirInfo;
foreach (string str in files)
{
    if (Directory.Exists(str))
    {
        dirInfo = new DirectoryInfo(str);  

        foreach(FileInfo fi in dirInfo.GetFiles())
        {
            Debug.WriteLine("File in dir " + fi.Name);
        }
    }
    else if (File.Exists(str))
    {
        fileInfo = new FileInfo(str);
        Debug.WriteLine("File " + str);
    }
}

Upvotes: 1

Related Questions