using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
namespace ThreadTest
{
public class FileSearch
{
private int threadCount;
object obj = new object();
private Stack<string> fileList;
private List<Thread> tlist;
private string serachStr;
private long c = 0;
public FileSearch(int theadCount, string dir, string _searchStr)
{
this.threadCount = theadCount;
fileList = new Stack<string>();
this.serachStr = _searchStr;
tlist = new List<Thread>();
string[] dirList = Directory.GetDirectories(dir);
foreach (string _dir in dirList)
{
fileList.Push(_dir);
}
SerachFile(dir);
}
public void Run()
{
if (threadCount <= 0) throw new Exception("线程数目必须大于零");
for (int i = 0; i < this.threadCount; i++)
{
Thread t = new Thread(new ThreadStart(Search));
tlist.Add(t);
t.Name = "线程" + (i + 1);
t.Start();
string str = string.Format("{0} 开始启动", t.Name);
}
}
private void Search()
{
string myStr = string.Format("{0} 进入查找............", Thread.CurrentThread.Name);
while (fileList.Count > 0)
{
string filePath = null;
lock (obj)
{
while (fileList.Count > 0)
{
filePath = fileList.Pop();
//string logInfo = string.Format("{0} 获取 目录 ", Thread.CurrentThread.Name, filePath);
break;
}
}
if (string.IsNullOrEmpty(filePath))
{
break;
}
try
{
string[] dirList = Directory.GetDirectories(filePath);
SerachFile(filePath);
if (dirList.Length > 0)
{
lock (obj)
{
foreach (string str in dirList)
{
// string logInfo = string.Format("{0} 添加 目录 ", Thread.CurrentThread.Name, str);
fileList.Push(str);
}
}
}
}
catch (Exception) { }
Thread.Sleep(1);
}
}
public void Complete()
{
foreach (Thread t in tlist)
{
t.Join();
}
Console.WriteLine("完成 共找到 " + c);
}
private void SerachFile(string filePath)
{
string[] curfileList = Directory.GetFiles(filePath);
foreach (string file in curfileList)
{
int endIndex = file.LastIndexOf('.');
int startindex = file.LastIndexOf('\\');
if (endIndex < startindex) continue;
string name = file.Substring(startindex + 1, endIndex - startindex);
if (name.IndexOf(serachStr) >= 0)
{
c++;
// Console.WriteLine(string.Format(" 找到 {0} 在文件 ", serachStr, file));
}
}
}
}
}