public System.Collections.Specialized.StringCollection GetAllFiles(string rootdir)
{
System.Collections.Specialized.StringCollection result = new System.Collections.Specialized.StringCollection();
GetAllFiles(rootdir,result);
return result;
}
public void GetAllFiles(string parentDir,System.Collections.Specialized.StringCollection result)
{
string[] dir = System.IO.Directory.GetDirectories(parentDir);
for (int i=0;i<dir.Length;i++)
GetAllFiles(dir[i],result);
string[] file = System.IO.Directory.GetFiles(parentDir);
for (int i=0;i<file.Length;i++)
result.Add(file[i]);
}
具体调用如下:
private void button1_Click(object sender, System.EventArgs e)
{
System.Collections.Specialized.StringCollection result = GetAllFiles(@"c:\myfiles\");
for (int i=0;i<result.Count;i++)
MessageBox.Show(result[i]);
}
-----------------------------------------------------------
用2个循环就解决了
string[] dir = System.IO.Directory.GetDirectories(parentDir);
for (int i=0;i<dir.Length;i++)
{
GetAllFiles(dir[i],result);
string[] file = System.IO.Directory.GetFiles(parentDir);
for (int i=0;i<file.Length;i++)
{
result.Add(file[i]);
}
}
-----------------------------------------------------------
//递归列出目录下的所有文件和子目录
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< 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--;//缩进减一
}