Search code examples
c#.netdrag-and-droptext-filesrichtextbox

Dragging files into rich textbox to read text in file


I'm having a problem with dragging and dropping files onto a richTextBox, every time I drag a text file onto it, it turns into a picture of the text file with its name under it. Double click the file and it opens up using the system default application (ie notepad for text files, etc). basically its making shortcuts in the richTextBox, when i want it to read the text in the file.

Based on this code, the text from the file should extract into richTextBox1

    class DragDropRichTextBox : RichTextBox
    {
    public DragDropRichTextBox()
    {
        this.AllowDrop = true;
        this.DragDrop += new DragEventHandler(DragDropRichTextBox_DragDrop);
    }

    private void DragDropRichTextBox_DragDrop(object sender, DragEventArgs e)
    {
        string[] fileNames = e.Data.GetData(DataFormats.FileDrop) as string[];

        if (fileNames != null)
        {
            foreach (string name in fileNames)
            {
                try
                {
                    this.AppendText(File.ReadAllText(name) + "\n");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
    }

Any ideas on how to make this work?


Solution

  • you need to check the draged object before you are reading into file. try below code.

     public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                richTextBox1.DragDrop += new DragEventHandler(richTextBox1_DragDrop);
                richTextBox1.AllowDrop = true;
            }
    
            void richTextBox1_DragDrop(object sender, DragEventArgs e)
            {
                object filename = e.Data.GetData("FileDrop");
                if (filename != null)
                {
                    var list = filename as string[];
    
                    if (list != null && !string.IsNullOrWhiteSpace(list[0]))
                    {
                        richTextBox1.Clear();
                        richTextBox1.LoadFile(list[0], RichTextBoxStreamType.PlainText);
                    }
    
                }
            }