using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
namespace 为硬盘文件建立索引
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 文件路径
/// </summary>
string fpath = "";
/// <summary>
/// 初始化路径
/// </summary>
/// <param name="rootDirectory"></param>
private void BeginWrite(string rootDirectory)
{
fpath = @rootDirectory + "index.txt";
}
/// <summary>
/// 写一行数据
/// </summary>
/// <param name="Text"></param>
private void WriteText(string Text)
{
File.AppendAllText(fpath, Text + "\r\n");
}
/// <summary>
/// 创建索引按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCreateIndex_Click(object sender, EventArgs e)
{
DriveInfo[] DriveInfos = DriveInfo.GetDrives();
foreach (DriveInfo di in DriveInfos)
{
if (di.DriveType == DriveType.Fixed)
{
string rootDirectory = di.RootDirectory.FullName;
///textBoxRoot.Text输入的盘符(如:H)
if (rootDirectory.StartsWith(textBoxRoot.Text.Trim().ToUpper()))
{
lbIndex.Visible = true;
btnCreateIndex.Enabled = false;
BeginWrite(rootDirectory);
Thread th = RunNew(CreateIndex, rootDirectory);
th.Join();//主线程等待线程th运行完毕
// CreateIndex(rootDirectory);
btnCreateIndex.Enabled = true;
lbIndex.Visible = false;
MessageBox.Show("成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
/// <summary>
/// 创建索引函数
/// </summary>
/// <param name="PareDirectory"></param>
private void CreateIndex(object PareDirectory)
{
string[] Files = Directory.GetFiles(PareDirectory.ToString());//文件列表
string[] DirectoryInfos = Directory.GetDirectories(PareDirectory.ToString());//文件夹列表
int DirectoryCount = DirectoryInfos.Length;//子文件夹个数
for (int k = 0; k < Files.Length; k++)
{
try
{
if (Files[k].Contains("$RECYCLE.BIN")) File.Delete(Files[k]);
else WriteText(Files[k]);
}
catch
{
continue;
}
}
for (int i = 0; i < DirectoryCount; i++)
{
try
{
if ((new DirectoryInfo(DirectoryInfos[i]).Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
continue;
}
CreateIndex(DirectoryInfos[i]);
}
catch
{
continue;
}
}
}
/// <summary>
/// 创建新线程
/// </summary>
/// <param name="vfunc"></param>
/// <param name="para"></param>
/// <returns></returns>
private Thread RunNew(myFunction vfunc, object para)
{
Thread th = new Thread(new ParameterizedThreadStart(vfunc));
th.Start(para);
return th;
}
private delegate void myFunction(object obj);
/// <summary>
/// 窗体加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
lbIndex.Visible = false;
}
}
}
我用这个方法把自己的移动硬盘上的$RECYCLE.BIN中的文件删除成功,然后还建议了索引文件。
如下:
本人邮箱:pukuimin@qq.com