bird

 

C#用正则表达式批量改文件名

用正则表达式批量改文件名,遍历文件目录,可以控制层数

        /// <summary>
        
/// 指定文件夹下文件名批量替换
        
/// </summary>
        
/// <param name="pattern">The pattern.</param>
        
/// <param name="replacement">The replacement.</param>
        
/// <param name="path">路径</param>
        
/// <param name="depth">扫描目录层数,0表示不限制层数</param>

        public static void FileNameReplace(string pattern,string replacement, string path, int depth)
        
{
            
if (depth < 0throw new Exception("depth must >=0");

                DirectoryInfo mainDir;
                mainDir 
= new DirectoryInfo(path);
                
//遍历文件
                foreach (FileInfo f in mainDir.GetFiles())
                
{
                    
//增加文件
                    string fileName=Regex.Replace(f.Name, pattern, replacement);
                    
//if (fileName != f.Name)WL(f.Name+" "+fileName);
                    try
                    
{
                        
if (fileName != f.Name) 
                        
{
                            f.MoveTo(Path.Combine(path, fileName));
                            Console.WriteLine(
"Replace "+f.Name+"to "+fileName);
                        }

                    }

                    
catch (Exception ex)
                    
{
                        Console.WriteLine(ex.Message);
                        
continue;
                    }

                }

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

                }

                
else if (depth == 1)
                
{
                }

                
else
                
{
                    
foreach (DirectoryInfo d in mainDir.GetDirectories())
                    
{
                        
//递归调用
                        FileNameReplace(pattern, replacement, Path.Combine(path, d.Name), depth - 1);
                    }

                }


        }


    
public static void Main()
    
{
        FileNameReplace(
@"(.*).htm"@"$1.jsp"@"\10.10.22.244zhong_ao_xin"0);
    }

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

导航