WinForm中ListView仅显示文件名同时保留路径打开文件的实现问题
实现思路
利用Winform ListViewItem 自带的 Tag 属性存储和列表项关联的自定义数据:
- 列表项显示文本(
Text属性)仅设置为文件名,满足UI展示需求 - 把文件的完整路径存到
Tag属性中,点击列表项时直接读取Tag即可拿到完整路径,无需额外拼接
原有代码问题说明
- 提前调用
Path.ChangeExtension(d, null)修改了原始完整路径,会导致后续File.GetLastWriteTime调用报错,也丢失了原始路径信息 - 重复调用
listView1.Items.Add两次,会生成重复的列表项 - 打开文件时拼接当前程序工作目录,和你搜索的D盘路径不匹配,无法正确定位文件
修正后代码
搜索加载部分
private void button1_Click(object sender, EventArgs e) { listView1.Items.Clear(); // 先保留原始完整路径,不要提前修改 IEnumerable<string> filesOrDirectories = FileDirectorySearcher.Search(@"D:\", "*" + textBox1.Text + "*"); foreach (string fullPath in filesOrDirectories) { DateTime dt = File.GetLastWriteTime(fullPath); // 要显示的文件名,不需要扩展名就换为Path.GetFileNameWithoutExtension(fullPath) string showName = Path.GetFileName(fullPath); ListViewItem lvi = new ListViewItem(showName); // 把完整路径存在Tag属性中备用 lvi.Tag = fullPath; lvi.SubItems.Add(dt.ToString()); // 只添加一次列表项即可 listView1.Items.Add(lvi); } }
点击打开部分
private void listView1_ItemActivate(object sender, EventArgs e) { if (listView1.SelectedItems.Count == 0) return; // 直接读取Tag中存储的完整路径 string fullPath = listView1.SelectedItems[0].Tag as string; if (!string.IsNullOrEmpty(fullPath) && File.Exists(fullPath)) { System.Diagnostics.Process.Start(fullPath); } }
如果搜索结果包含目录,需要支持点击打开目录,只需将打开部分的存在性判断修改为File.Exists(fullPath) || Directory.Exists(fullPath)即可。
内容的提问来源于stack exchange,提问作者petule.08
相关产品推荐
相关产品推荐

