将文件拖入富文本框以读取文件中的文本

Kaz*_*oph 1 .net c# drag-and-drop richtextbox text-files

我在将文件拖放到 richTextBox 上时遇到问题,每次将文本文件拖到其上时,它都会变成文本文件的图片,其名称位于其下方。双击该文件,它会使用系统默认应用程序(即用于文本文件的记事本等)打开。基本上,当我希望它读取文件中的文本时,它会在 richTextBox 中创建快捷方式。

根据此代码,文件中的文本提取到 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);
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

关于如何实现这项工作有什么想法吗?

JSJ*_*JSJ 5

在读入文件之前,您需要检查拖动的对象。尝试下面的代码。

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

            }
        }
Run Code Online (Sandbox Code Playgroud)