Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only a text file in drag drop on a textbox using C#.Net

I am working on a Windows Forms Application.

During one Drag and Drop action on a TextBox control, I want to restrict the user to provide only a text file.

// drag drop module for input text file in textbox starts here
private void textBoxInputTextFile_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
        e.Effect = DragDropEffects.Copy;
    else
        e.Effect = DragDropEffects.None;
}

private void textBoxInputTextFile_DragDrop(object sender, DragEventArgs e)
{
    if(e.Data.GetData(DataFormats.FileDrop, true))
    {
    // Check if it is a text file
    // Okay if it is a text file or else give an error message
    }
}

This code is just a sample from my previous folder drop action but now I want to restrict it to only one file and that too must be a text file. So that, when the drop action happens, it should check first if it is a text file or not and then do other stuff.

How do I do that?

like image 677
Indigo Avatar asked Nov 01 '12 10:11

Indigo


1 Answers

Written off the top of my head (untested):

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

foreach(var file in files)
{
    if(System.IO.Path.GetExtension(file).Equals(".txt", StringComparison.InvariantCultureIgnoreCase))
    {
        //file has correct extension, do something with file
    }
    else
    {
        MessageBox.Show("Not a text file");
    }
}

Before putting this sort of thing into production, I'd probably add more null checks (what if a file doesn't have an extension for example?) but this should give you the basic idea.

If you want some kind of more stringent test to see if the file being dropped is a text file rather than just check it's extension, I'd recommend reading this SO question.

like image 74
Bridge Avatar answered Oct 20 '22 10:10

Bridge