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

通过递归法遍历文件目录,判断指定文件是否存在的一个函数,可以设定遍历目录层数.
         /// <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;
            }

        }

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值