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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With