文件拖放到TextBox控件上提取路径

这篇博客介绍了如何在Windows Forms应用程序中,使用C#实现文本框支持文件拖放的功能。通过注册DragDrop和DragEnter事件以及设置AllowDrop属性,可以允许用户将文件拖放到文本框中,从而将文件路径显示在文本框内。

先看效果

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox_DragPathInit(textBox1); //注册texBbox1 支持拖拽
            textBox_DragPathInit(textBox2); //注册texBbox2 支持拖拽
        }

        private void textBox_DragPathInit(object sender)
        {
            //this.textBox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.textBox1_DragDrop);
            //this.textBox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.textBox1_DragEnter);
            //textBox1.AllowDrop = true;
            ((System.Windows.Forms.TextBox)sender).DragDrop += new System.Windows.Forms.DragEventHandler(this.textBox_DragDrop);
            ((System.Windows.Forms.TextBox)sender).DragEnter += new System.Windows.Forms.DragEventHandler(this.textBox_DragEnter);
            ((System.Windows.Forms.TextBox)sender).AllowDrop = true;
        }

        //参考链接
        // http://www.luofenming.com/show.aspx?id=dbad2a805bc4453698dfdae8aa841bbd
        private void textBox_DragDrop(object sender, DragEventArgs e)
        {
            ((System.Windows.Forms.TextBox)sender).Text = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
        }

        private void textBox_DragEnter(object sender, DragEventArgs e)
        {
            //文件拖放处理
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
    }
}

大家可以搜索罗分明这位博主,代码中也保留了链接。 

特此记录

anlog

2022年9月15日

好的!在你之前需求的基础上继续完善: --- ### ✅ 最新需求明确 1. **读取共享路径下的 CSV 文件**: ``` \\10.197.24.180\PACK Sanyo program\PC name check log\Save PC name.CSV ``` 2. **文件结构要求**: - 第1、第2行为空行。 - 数据从第3行开始,每行最多 5 个计算机名,逗号分隔。 3. **功能目标**: - 读取**最后一行非空行**的计算机名。 - 将这些名称存储在一个名为 `PCdata` 的字符串数组中(即:`Dim PCdata() As String`)。 - 将 `PCdata` 中的内容以逗号分隔的形式显示在 `TextBox1` 中(例如:`PC01, PC02, PC03`)。 - 如果没有数据,则 `TextBox1` 显示为空或提示信息(可配置)。 > ✅ 特点:只读、安全、带编码处理、异常防护。 --- ### ✅ 完整 VB.NET 代码实现 ```vb ''' <summary> ''' 读取共享 CSV 文件提取最后一行计算机名存入 PCdata 数组,并显示在 TextBox1 ''' </summary> Private Sub LoadLastLineIntoPCdata() ' 声明全局/模块级变量 PCdata (若已在类级别声明,此处仅为赋值) Static PCdata() As String = {} ' 可改为 Class 级别变量 ' 共享文件路径 Dim SaveDataFileName As String = "\\10.197.24.180\PACK Sanyo program\PC name check log\Save PC name.CSV" ' 初始化临时列表用于收集电脑名 Dim tempList As New List(Of String) Try ' 检查共享目录是否存在 Dim dir As String = Path.GetDirectoryName(SaveDataFileName) If Not Directory.Exists(dir) Then SetTextBoxText(TextBox1, "错误:共享目录不存在,请检查网络连接。") PCdata = {} Return End If ' 检查文件是否存在 If Not File.Exists(SaveDataFileName) Then SetTextBoxText(TextBox1, "提示:CSV 文件不存在。") PCdata = {} Return End If ' 使用 Shift-JIS 编码读取所有行(防止日文乱码) Dim lines As String() = File.ReadAllLines(SaveDataFileName, Encoding.GetEncoding("Shift-JIS")) ' 转为 List 方便操作 Dim lineList As New List(Of String)(lines) ' 确保至少有两行(格式预留) While lineList.Count < 2 lineList.Add("") End While ' 从后往前查找最后一个非空行 Dim lastNonEmptyIndex As Integer = -1 For i As Integer = lineList.Count - 1 To 0 Step -1 If Not String.IsNullOrWhiteSpace(lineList(i)) Then lastNonEmptyIndex = i Exit For End If Next ' 若无有效数据行 If lastNonEmptyIndex = -1 Then SetTextBoxText(TextBox1, "无登记记录") PCdata = {} Return End If ' 解析最后一行内容 Dim lastLine As String = lineList(lastNonEmptyIndex).Trim() If Not String.IsNullOrEmpty(lastLine) Then tempList.AddRange( lastLine.Split(","c).Select(Function(s) s.Trim()).Where(Function(s) Not String.IsNullOrEmpty(s))) End If ' 将结果保存到全局数组 PCdata PCdata = tempList.ToArray() ' 显示在 TextBox1:用逗号+空格连接 Dim displayText As String = If(PCdata.Length > 0, String.Join(", ", PCdata), "(最新批次为空)") SetTextBoxText(TextBox1, displayText) Catch ex As UnauthorizedAccessException SetTextBoxText(TextBox1, "权限不足,无法访问文件。") PCdata = {} Catch ex As IO.IOException SetTextBoxText(TextBox1, "文件读取失败(网络中断或被占用)") PCdata = {} Catch ex As Exception SetTextBoxText(TextBox1, "未知错误:" & ex.Message) PCdata = {} End Try End Sub ''' <summary> ''' 安全设置 TextBox 文本(支持跨线程调用) ''' </summary> Private Sub SetTextBoxText(tb As TextBox, text As String) If tb.InvokeRequired Then tb.Invoke(New Action(Of TextBox, String)(AddressOf SetTextBoxText), tb, text) Else tb.Text = text End If End Sub ``` --- ### 🔧 如何使用?(示例:按钮触发加载) ```vb ' 在窗体上放一个按钮 Button1 和一个 TextBox1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click LoadLastLineIntoPCdata() End Sub ``` --- ### 📦 控件设置建议 - `TextBox1`: - `Multiline = False`(单行显示) - 或 `Multiline = True`, `ReadOnly = True`, `ScrollBars = Horizontal`(更清晰展示) --- ### 💡 示例效果 #### 情况一:最后一行是 `PC08,PC09` → `PCdata = {"PC08", "PC09"}` → `TextBox1.Text = "PC08, PC09"` #### 情况二:无数据 → `PCdata = {}` → `TextBox1.Text = "无登记记录"` #### 情况三:文件路径不可达 → `TextBox1.Text = "错误:共享目录不存在..."` --- ### ⚠️ 注意事项 | 项目 | 说明 | |------|------| | `PCdata` 存储位置 | 推荐将其定义为 **类级别变量**,以便其他函数也能访问 | | 编码问题 | 必须使用 `Shift-JIS` 读取,否则日文系统会乱码 | | 异常安全 | 所有 IO 错误都被捕获,不会导致程序崩溃 | | 跨线程安全 | 使用 `Invoke` 防止异步调用时报错 | #### ✅ 类级别声明 PCdata(推荐写法) ```vb Public Class Form1 Private PCdata() As String ' 在类中声明,供多个方法使用 ' 其他方法... End Class ``` 然后去掉 `Static PCdata()` 即可。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值