实现效果如下图:
功能:实现查找文件名包含输入关键字的文件
实现代码:
导入命名空间:
using System.Threading;
using System.Diagnostics;
引用dll System.Windows.Forms
1.选择要查找的文件夹路径:代码如下
/// <summary>
/// 选择路径事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, RoutedEventArgs e)
{
System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.txtPath.Text = fbd.SelectedPath;
}
}
2.输入关键字,点击查找
Thread t;
string folderPath = string.Empty;
string strKeyWord = string.Empty;
/// <summary>
/// 查找文件名包含输入文字的文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, RoutedEventArgs e)
{
this.txtProcess.Text = string.Empty;
this.progressBar1.Value = 0;
//检查路径是否正确
if (CheckInput() == false)
{
return;
}
folderPath = this.txtPath.Text;
strKeyWord = this.txtName.Text.Trim();
t = new Thread(Method);
t.Start();
}
3.以上事件用到的方法
/// <summary>
/// 检查路径的正确性
/// </summary>
/// <returns></returns>
private bool CheckInput()
{
if (this.txtPath.Text.Trim() == string.Empty)
{
MessageBox.Show("请输入文件夹路径。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
this.txtPath.Focus();
return false;
}
string strFolderName = this.txtPath.Text.Trim();
try
{
string[] fileInfo = Directory.GetFiles(strFolderName);
if (fileInfo.Length <= 0)
{
MessageBox.Show("该文件下没有文件。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
this.txtPath.Focus();
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
this.txtPath.Focus();
return false;
}
return true;
}
private void Method()
{
FindFiles();
this.progressBar1.Dispatcher.Invoke(new Action(() => { this.progressBar1.Value = 100; }));
this.lblPercent.Dispatcher.Invoke(new Action(() => { this.lblPercent.Content = "100%"; }));
}
/// <summary>
/// 查找文件
/// </summary>
private void FindFiles()
{
string[] fileNames = Directory.GetFiles(folderPath);
var first = fileNames.Count(p => p.Contains(strKeyWord));
this.progressBar1.Dispatcher.Invoke(new Action(() => { this.progressBar1.Maximum = (double)first; }));
int i = 0;
foreach (var file in fileNames)
{
if (file.Contains(strKeyWord))
{
i++;
this.txtProcess.Dispatcher.Invoke(new Action(() => { this.txtProcess.Text = txtProcess.Text + "找到文件" + file + "
"; }));
Thread.Sleep(100);
this.lblPercent.Dispatcher.Invoke(new Action(() =>
{
string str = (progressBar1.Value / (double)first * 100).ToString();
if (str.Length > 4)
{
str = str.Substring(0, 5);
}
this.lblPercent.Content = str + "%";
}));
this.progressBar1.Dispatcher.Invoke(new Action(() =>
{
this.progressBar1.Value = progressBar1.Value + 1;
}));
}
}
}