gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:18:07 25 4
gpt4 key购买 nike

我在将文件拖放到 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);
}
}
}
}

关于如何使这项工作有任何想法吗?

最佳答案

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

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

}
}

关于c# - 将文件拖入富文本框以读取文件中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15333457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com