日期:2014-05-17  浏览次数:20831 次

C#批量去掉文件前缀,最近用动软代码生成器,文件名在代码里改不了。
        static void Main(string[] args)
        {
            Console.WriteLine("本程序去掉当前目录及子目录下的文件前缀");
            Console.Write("请输入要去掉的前缀:");
            string stringFront = Console.ReadLine();
            if (stringFront != "")
            {
                string dir = AppDomain.CurrentDomain.BaseDirectory;
                RenameFile(dir, stringFront);
            }
            else Console.WriteLine("请输入要去掉的前缀!");
            Console.WriteLine("操作已完成");
            Console.ReadKey();
        }
        public static void RenameFile(string ParentDir,string stringFront)
        {
            string[] files = Directory.GetFiles(ParentDir, "*.cs", SearchOption.TopDirectoryOnly);
            foreach (string file in files)
            {
                string filename = Path.GetFileName(file);
                string pathname = Path.GetDirectoryName(file);

                if (filename.StartsWith(stringFront, true, null))
                {
                    filename = filename.Substring(stringFront.Length);
                    FileInfo fi = new FileInfo(file);
                    fi.MoveTo(Path.Combine(pathname,filename));
                }
            }
            string[] dirs = Directory.GetDirectories(ParentDir);
            foreach(string dir in dirs)
            {
                RenameFile(dir,stringFront);
            }
        }