Windows Forms: Drag and Drop text files into a RichTextBox in C#

This post shows you How to drag and drop text files into a RichTextBox in C# Windows Forms Application.

In C#, you can easily enable drag-and-drop functionality for a RichTextBox control by handling the appropriate events and setting the AllowDrop property to true.

How to drag and drop text files into a RichTextBox in C#

Here's a step-by-step guide on how to achieve this.

Create a simple demo in c# Windows Forms Application, then drag and drop a RichTextBox control onto your form from the Visual Studio toolbox.

drag files into richtextbox c#

Enable Drag-and-Drop: Set the AllowDrop property of the RichTextBox control to true.

Handle DragEnter Event: Implement the DragEnter event handler to specify the types of data that can be dragged into the control.

private void RichTextBox1_DragEnter(object sender, DragEventArgs e)
{
    // Check if the data being dragged is of type FileDrop
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effect = DragDropEffects.Copy; // Set the effect to Copy
    }
    else
    {
        e.Effect = DragDropEffects.None; // Indicate that the drop is not allowed
    }
}

Handle DragDrop Event: Implement the DragDrop event handler to handle the drop operation and process the dropped data.

Add a Form1_Load event handler to your form allows you to drag and drop files into RichTextBox control as the following c# code.

private void Form1_Load(object sender, EventArgs e)
{
    richTextBox1.AllowDrop = true;
    richTextBox1.DragDrop += RichTextBox1_DragDrop;
}

Add the DragDrop event handler to RichTextBox allows you to read the file from your disk as shown below.

private void RichTextBox1_DragDrop(object sender, DragEventArgs e)
{
    var data = e.Data.GetData(DataFormats.FileDrop);
    if (data != null)
    {
        var fileNames = data as string[];
        if (fileNames.Length > 0)
            richTextBox1.LoadFile(fileNames[0]);
    }
}

RichTextBox1_DragDrop: This event handler processes the drop operation. It retrieves the file paths of the dropped files.

If you want to read multiple files you can use for each file, then checks if it's a text file (.txt) and if so, reads the text from the file and appends it to the RichTextBox.

private void RichTextBox1_DragDrop(object sender, DragEventArgs e)
{
    // Get the array of file paths being dragged
    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

    // Iterate through each file
    foreach (string file in files)
    {
        // Check if it's a text file
        if (System.IO.Path.GetExtension(file).ToLower() == ".txt")
        {
            // Read the text from the file
            string text = System.IO.File.ReadAllText(file);

            // Append the text to the RichTextBox
            richTextBox1.AppendText(text);
        }
    }
}

Press F5 to run your application, then try to drag and drop the files into RichTextBox control.

VIDEO TUTORIAL