bird

 

扫描指定文件夹下是否存在某一文件

通过递归法遍历文件目录,判断指定文件是否存在的一个函数,可以设定遍历目录层数.
        /// <summary>
        
/// 扫描指定文件夹下是否存在某一文件
        
/// </summary>
        
/// <param name="filename">文件名</param>
        
/// <param name="path">路径</param>
        
/// <param name="depth">扫描目录层数,0表示不限制层数</param>
        
/// <returns>true/false</returns>

        public static bool FileExist(string filename, string path, int depth)
        
{
            
if (depth < 0throw new Exception("depth must >=0");
            
try
            
{
                DirectoryInfo mainDir;
                mainDir 
= new DirectoryInfo(path);
                
//遍历文件
                foreach (FileInfo f in mainDir.GetFiles())
                
{
                    
//增加文件
                    if (filename.ToLower() == f.Name.ToLower())
                    
{
                        
return true;
                    }

                }

                
//遍历文件目录
                if (depth == 0)
                
{
                    
foreach (DirectoryInfo d in mainDir.GetDirectories())
                    
{
                        
//递归调用
                        if (FileExist(filename, Path.Combine(path, d.Name), 0))
                            
return true;
                    }

                }

                
else if (depth == 1)
                
{
                }

                
else
                
{
                    
foreach (DirectoryInfo d in mainDir.GetDirectories())
                    
{
                        
//递归调用
                        if (FileExist(filename, Path.Combine(path, d.Name), depth - 1))
                            
return true;
                    }

                }

                
return false;
            }

            
catch (Exception)
            
{
                
return false;
            }

        }

posted on 2007-08-22 15:08  鸟人  阅读(277)  评论(0编辑  收藏  举报

导航