搜索目录里所有文件(包括子目录)
资料来源:http://www.cnblogs.com/jjwwww/archive/2004/09/04/39559.aspx
用到两个函数ParseDirectory 和CreatePathList
void ParseDirectory(string path, string filter)
{
string[] dirs = Directory.GetDirectories(path);//得到子目录
IEnumerator iter = dirs.GetEnumerator();
while(iter.MoveNext())
{
string str = (string)(iter.Current);
ParseDirectory(str, filter);
}
string[] files = Directory.GetFiles(path, filter);
if(files.Length > 0)
{
m_numFiles += files.Length;
m_pathList.Add(files);
}
}
{
string[] dirs = Directory.GetDirectories(path);//得到子目录
IEnumerator iter = dirs.GetEnumerator();
while(iter.MoveNext())
{
string str = (string)(iter.Current);
ParseDirectory(str, filter);
}
string[] files = Directory.GetFiles(path, filter);
if(files.Length > 0)
{
m_numFiles += files.Length;
m_pathList.Add(files);
}
}
string[] CreatePathList()
{
if(m_numFiles <= 0)
{
return null;
}
string[] str = new string[m_numFiles];
int index = 0;
try
{
IEnumerator pathIter = m_pathList.GetEnumerator();
while(pathIter.MoveNext())
{
string[] ar = (string[])(pathIter.Current);
IEnumerator fileIter = ar.GetEnumerator();
while(fileIter.MoveNext())
{
str[index] = (string)(fileIter.Current);
++index;
}
}
}
catch(Exception e)
{
return null;
}
return str;
}
{
if(m_numFiles <= 0)
{
return null;
}
string[] str = new string[m_numFiles];
int index = 0;
try
{
IEnumerator pathIter = m_pathList.GetEnumerator();
while(pathIter.MoveNext())
{
string[] ar = (string[])(pathIter.Current);
IEnumerator fileIter = ar.GetEnumerator();
while(fileIter.MoveNext())
{
str[index] = (string)(fileIter.Current);
++index;
}
}
}
catch(Exception e)
{
return null;
}
return str;
}
# 非递归实现re: 搜索目录里所有文件(包括子目录)
void ParseDirectory(string path, string filter)
{
Queue q=new Queue();
q.Enqueue(path);
while(q.Count > 0) {
string path=(string)q.Dequeue();
string[] files = Directory.GetFiles(path,filter);
if(files.Length > 0) {
m_numFiles += files.Length;
m_pathList.Add(files);
}
string[] dirs = Directory.GetDirectories(path);
foreach(string dir in dirs){
q.Enqueue(dir);
}
}
}
使用范例:如果要查找的:d目录下所有mp3文件
string path="d:\\"; //目录名 也可以用相当路径
string filter="*.mp3"; //文件类型
int m_numFiles=0; //文件总数
ArrayList m_pathList = new ArrayList();//包含所有文件路径的数组
string[] files; //所有文件名
ParseDirectory(path, "*.mp3");
files=CreatePathList(); //生成文件名数组
if(files == null)
{
throw new Exception(String.Concat("No file found in ", path));
}