gpt4 book ai didi

c# - 使用 C#.Net 仅允许在文本框上拖放文本文件

转载 作者:行者123 更新时间:2023-11-30 14:34:54 25 4
gpt4 key购买 nike

我正在开发 Windows 窗体应用程序。

在对 TextBox 控件执行拖放操作期间,我想限制用户仅提供一个文本文件。

// drag drop module for input text file in textbox starts here
private void textBoxInputTextFile_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}

private void textBoxInputTextFile_DragDrop(object sender, DragEventArgs e)
{
if(e.Data.GetData(DataFormats.FileDrop, true))
{
// Check if it is a text file
// Okay if it is a text file or else give an error message
}
}

此代码只是我之前的文件夹放置操作的一个示例,但现在我想将它限制为只有一个文件,而且它也必须是一个文本文件。因此,当放置 Action 发生时,它应该首先检查它是否是一个文本文件,然后再做其他事情。

我该怎么做?

最佳答案

写在我的头顶(未经测试):

var files = (string[])e.Data.GetData(DataFormats.FileDrop);

foreach(var file in files)
{
if(System.IO.Path.GetExtension(file).Equals(".txt", StringComparison.InvariantCultureIgnoreCase))
{
//file has correct extension, do something with file
}
else
{
MessageBox.Show("Not a text file");
}
}

在将这类东西投入生产之前,我可能会添加更多的空检查(例如,如果文件没有扩展名怎么办?)但这应该给你基本的想法。

如果你想要某种更严格的测试来查看被删除的文件是否是文本文件而不是仅仅检查它的扩展名,我建议阅读 this SO question .

关于c# - 使用 C#.Net 仅允许在文本框上拖放文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13175133/

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