日期:2011-12-16  浏览次数:20446 次

把自己的资料刻录成很多光盘,发现连自己都很难找到需要的文件在哪张光盘上,因此我就根据需求,在Visual Studio.NET中写了一个列出目录下所有子目录和文件的程序,以方便我列出刻录的资料光盘上的所有文件信息。

本程序的主要算法是递归,主函数如下:

//递归列出目录下的所有文件和子目录

public void ListFiles( FileSystemInfo fileinfo )

{

if( ! fileinfo.Exists ) return;

DirectoryInfo dirinfo = fileinfo as DirectoryInfo;

if( dirinfo == null ) return; //不是目录

indent++;//缩进加一

FileSystemInfo [] files = dirinfo.GetFileSystemInfos();

for( int i=0; i遍历目录下所有文件、子目录

{

FileInfo file = files[i] as FileInfo;

if( file != null ) // 是文件

{

this.richTextBox1.Text+=(WriteSpace(indent)+"|-"+

file.Name + "\t" + ConvertToKByte(file.Length)+"\r" );

}

else //是目录

{

this.richTextBox1.Text+=(WriteSpace(indent)+"+"+files[i].FullName+"\r");

ListFiles( files[i] ); //对子目录进行递归调用

}

}

indent--;//缩进减一

}

程序的设计界面如下图所示:


控件有两个Button控件btnSelect和btnSave(分别用来选择目录和保存文件);一个RichTextBox控件(显示结果),一个folderBrowserDialog控件(选择目录)和一个saveFileDialog控件(选择保存文件路径)。

程序运行后的界面如下图所示:







程序的完整代码如下:(其中红色的是我自己添加的)

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Globalization;

using System.IO;



namespace ListFile_Windows

{

///

/// Form1 的摘要说明。

///

public class Form1 : System.Windows.Forms.Form

{

private System.Windows.Forms.RichTextBox richTextBox1;

public static int indent; //缩进值

private System.Windows.Forms.Button btnSelect;

private System.Windows.Forms.Button btnSave;

private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;

private System.Windows.Forms.SaveFileDialog saveFileDialog1;

///

/// 必需的设计器变量。

///

private System.ComponentModel.Container components = null;



public Form1()

{

//

// Windows 窗体设计器支持所必需的

//

InitializeComponent();



//

// TODO: 在 InitializeComponent 调用后添加任何构造函数代码

//

}



///

/// 清理所有正在使用的资源。

///

protected override void Dispose( bool disposing )

{

if( disposing )