拖动文件到丰富的文本框来读取文件中的文本

问题描述:

我在使用拖放文件到一个RichTextBox一个问题,我每次拖动一个文本文件到它,它会变成一个带有不同的名称的文本文件的图像。双击该文件,并打开了使用系统默认应用程序(如记事本的文本文件等)。基本上,当我要在RichTextBox的,其制作的快捷方式到读取文件中的文本。

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.

,从文件中的文本提取到richTextBox1

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?

您需要检查draged对象之前,您正在阅读到文件中。试试下面code。

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);
                }

            }
        }