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中的文件刪除成功,然後還建議了索引文件。
如下:
作者:pukuimin1226