C# 本地文件搜索工具(带双击定位功能)
·
C#本地文件搜索工具,支持关键词搜索、文件类型过滤,并可以通过双击搜索结果在资源管理器中定位文件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace FileSearchTool
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
InitializeUI();
}
private void InitializeUI()
{
// 设置窗体属性
this.Text = "本地文件搜索工具";
this.Size = new Size(800, 600);
this.StartPosition = FormStartPosition.CenterScreen;
this.Icon = SystemIcons.Application;
// 创建控件
var lblPath = new Label { Text = "搜索路径:", Location = new Point(20, 20), AutoSize = true };
txtPath = new TextBox { Location = new Point(100, 17), Size = new Size(400, 25), Text = @"C:\" };
var btnBrowse = new Button { Text = "浏览...", Location = new Point(510, 15), Size = new Size(75, 25) };
btnBrowse.Click += BtnBrowse_Click;
var lblKeyword = new Label { Text = "关键词:", Location = new Point(20, 50), AutoSize = true };
txtKeyword = new TextBox { Location = new Point(100, 47), Size = new Size(200, 25) };
var lblFileType = new Label { Text = "文件类型:", Location = new Point(20, 80), AutoSize = true };
cmbFileType = new ComboBox { Location = new Point(100, 77), Size = new Size(150, 25), DropDownStyle = ComboBoxStyle.DropDownList };
cmbFileType.Items.AddRange(new object[] { "所有文件", "文档 (.doc;.docx;.pdf)", "图片 (.jpg;.png;.gif)", "代码 (.cs;.java;.py)", "压缩文件 (.zip;.rar)" });
cmbFileType.SelectedIndex = 0;
var chkRecursive = new CheckBox { Text = "递归搜索子目录", Location = new Point(260, 80), AutoSize = true, Checked = true };
var btnSearch = new Button { Text = "搜索", Location = new Point(400, 45), Size = new Size(100, 30) };
btnSearch.Click += BtnSearch_Click;
var progressBar = new ProgressBar { Location = new Point(20, 110), Size = new Size(565, 20), Visible = false };
lstResults = new ListView { Location = new Point(20, 140), Size = new Size(740, 350), View = View.Details, FullRowSelect = true, GridLines = true };
lstResults.Columns.Add("文件名", 200);
lstResults.Columns.Add("路径", 400);
lstResults.Columns.Add("大小", 100);
lstResults.Columns.Add("修改日期", 120);
lstResults.DoubleClick += LstResults_DoubleClick;
var statusLabel = new Label { Text = "就绪", Location = new Point(20, 500), AutoSize = true, Name = "statusLabel" };
// 添加控件到窗体
this.Controls.Add(lblPath);
this.Controls.Add(txtPath);
this.Controls.Add(btnBrowse);
this.Controls.Add(lblKeyword);
this.Controls.Add(txtKeyword);
this.Controls.Add(lblFileType);
this.Controls.Add(cmbFileType);
this.Controls.Add(chkRecursive);
this.Controls.Add(btnSearch);
this.Controls.Add(progressBar);
this.Controls.Add(lstResults);
this.Controls.Add(statusLabel);
// 保存引用
this.btnSearch = btnSearch;
this.btnBrowse = btnBrowse;
this.txtPath = txtPath;
this.txtKeyword = txtKeyword;
this.cmbFileType = cmbFileType;
this.chkRecursive = chkRecursive;
this.lstResults = lstResults;
this.progressBar = progressBar;
this.statusLabel = statusLabel;
}
// 控件声明
private TextBox txtPath;
private TextBox txtKeyword;
private ComboBox cmbFileType;
private CheckBox chkRecursive;
private Button btnSearch;
private Button btnBrowse;
private ListView lstResults;
private ProgressBar progressBar;
private Label statusLabel;
// 浏览文件夹
private void BtnBrowse_Click(object sender, EventArgs e)
{
using (var folderDialog = new FolderBrowserDialog())
{
folderDialog.Description = "选择搜索目录";
folderDialog.SelectedPath = txtPath.Text;
if (folderDialog.ShowDialog() == DialogResult.OK)
{
txtPath.Text = folderDialog.SelectedPath;
}
}
}
// 执行搜索
private void BtnSearch_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtPath.Text) || !Directory.Exists(txtPath.Text))
{
MessageBox.Show("请选择有效的搜索路径", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
lstResults.Items.Clear();
progressBar.Visible = true;
progressBar.Style = ProgressBarStyle.Marquee;
statusLabel.Text = "正在搜索...";
btnSearch.Enabled = false;
// 在后台线程执行搜索
Task.Run(() => SearchFiles());
}
// 文件搜索逻辑
private void SearchFiles()
{
try
{
string path = txtPath.Text;
string keyword = txtKeyword.Text.Trim();
bool recursive = chkRecursive.Checked;
string fileType = cmbFileType.SelectedItem.ToString();
// 获取文件扩展名过滤器
string[] extensions = GetExtensionsForFileType(fileType);
// 执行搜索
var files = Directory.EnumerateFiles(path, "*.*",
recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
.Where(file =>
{
// 检查文件类型
if (extensions != null && extensions.Length > 0)
{
string ext = Path.GetExtension(file).ToLower();
if (!extensions.Contains(ext)) return false;
}
// 检查关键词
if (!string.IsNullOrEmpty(keyword))
{
string fileName = Path.GetFileName(file);
if (!fileName.Contains(keyword, StringComparison.OrdinalIgnoreCase))
return false;
}
return true;
})
.ToList();
// 更新UI
this.Invoke((MethodInvoker)delegate {
progressBar.Visible = false;
btnSearch.Enabled = true;
statusLabel.Text = $"找到 {files.Count} 个文件";
foreach (string file in files)
{
try
{
var fileInfo = new FileInfo(file);
var item = new ListViewItem(Path.GetFileName(file));
item.SubItems.Add(Path.GetDirectoryName(file));
item.SubItems.Add(FormatFileSize(fileInfo.Length));
item.SubItems.Add(fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm"));
item.Tag = file; // 保存完整路径
lstResults.Items.Add(item);
}
catch
{
// 忽略无法访问的文件
}
}
});
}
catch (Exception ex)
{
this.Invoke((MethodInvoker)delegate {
progressBar.Visible = false;
btnSearch.Enabled = true;
statusLabel.Text = "搜索出错";
MessageBox.Show($"搜索过程中发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
});
}
}
// 根据选择的文件类型获取扩展名
private string[] GetExtensionsForFileType(string fileType)
{
switch (fileType)
{
case "文档 (.doc;.docx;.pdf)":
return new[] { ".doc", ".docx", ".pdf", ".txt", ".rtf" };
case "图片 (.jpg;.png;.gif)":
return new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
case "代码 (.cs;.java;.py)":
return new[] { ".cs", ".java", ".py", ".cpp", ".h", ".js", ".html", ".css" };
case "压缩文件 (.zip;.rar)":
return new[] { ".zip", ".rar", ".7z", ".tar", ".gz" };
default: // 所有文件
return null;
}
}
// 格式化文件大小
private string FormatFileSize(long bytes)
{
string[] sizes = { "B", "KB", "MB", "GB" };
int order = 0;
double len = bytes;
while (len >= 1024 && order < sizes.Length - 1)
{
order++;
len /= 1024;
}
return $"{len:0.##} {sizes[order]}";
}
// 双击打开文件所在位置
private void LstResults_DoubleClick(object sender, EventArgs e)
{
if (lstResults.SelectedItems.Count == 0) return;
string filePath = lstResults.SelectedItems[0].Tag as string;
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
{
MessageBox.Show("文件不存在或已被移动", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
try
{
// 在资源管理器中打开并选中文件
Process.Start("explorer.exe", $"/select, \"{filePath}\"");
}
catch (Exception ex)
{
MessageBox.Show($"无法打开文件位置: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
使用说明
功能特点
-
多条件搜索:
-
按路径搜索
-
按文件名关键词搜索
-
按文件类型过滤(文档、图片、代码、压缩文件等)
-
支持递归搜索子目录
-
-
结果展示:
-
显示文件名、完整路径、大小和修改日期
-
表格形式清晰展示
-
支持按列排序
-
-
文件定位:
-
双击搜索结果在资源管理器中打开文件所在位置
-
自动选中目标文件
-
-
用户体验:
-
进度条显示搜索状态
-
状态栏显示结果数量
-
错误处理和提示
使用步骤
-
设置搜索路径(默认为C:\)
-
输入文件名关键词(可选)
-
选择文件类型(默认为"所有文件")
-
选择是否递归搜索子目录
-
点击"搜索"按钮开始搜索
-
在结果列表中双击文件定位到该文件
扩展功能建议
-
添加书签功能:保存常用搜索路径
-
添加搜索历史:记录最近搜索的关键词
-
添加预览功能:在侧边栏显示文件内容预览
-
添加导出功能:将搜索结果导出为CSV或Excel
-
添加右键菜单:提供更多文件操作选项
参考代码 C# 搜索本地文件 例子源码(双击可定位到指定文件) www.youwenfan.com/contentcsv/116198.html
技术要点
文件搜索实现
// 使用LINQ进行高效文件搜索
var files = Directory.EnumerateFiles(path, "*.*",
recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
.Where(file =>
{
// 文件类型过滤
if (extensions != null && extensions.Length > 0)
{
string ext = Path.GetExtension(file).ToLower();
if (!extensions.Contains(ext)) return false;
}
// 关键词过滤
if (!string.IsNullOrEmpty(keyword))
{
string fileName = Path.GetFileName(file);
if (!fileName.Contains(keyword, StringComparison.OrdinalIgnoreCase))
return false;
}
return true;
})
.ToList();
文件定位实现
// 在资源管理器中打开并选中文件
Process.Start("explorer.exe", $"/select, \"{filePath}\"");
文件大小格式化
private string FormatFileSize(long bytes)
{
string[] sizes = { "B", "KB", "MB", "GB" };
int order = 0;
double len = bytes;
while (len >= 1024 && order < sizes.Length - 1)
{
order++;
len /= 1024;
}
return $"{len:0.##} {sizes[order]}";
}
使用场景
-
快速查找本地文件
-
批量处理特定类型文件
-
定位遗忘位置的重要文件
-
分析磁盘空间使用情况
-
查找大文件或旧文件
更多推荐
所有评论(0)