繁体   English   中英

批量替换或删除文件名中的字符

[英]Bulk replace or remove a character in file names

我正在编写一个小实用程序,该实用程序将允许用户从用户选择的特定目录中的文件名中用一个字符替换另一个字符。
这个想法是让用户用他们想要的任何其他字符替换“ _”或他们想要的任何其他字符,或者将其完全删除。

编辑:在获得了我从您的回答中获得的信息以及一些Google搜索以了解这些命令的工作方式后,我想到了这段代码。 任何反馈都很好。

    private static void myremovechar()
    {
        //subprocedure to modify file names by removing or replacing characters   NO SUB DIRECTORIES

        //Ask user where the files are located and store value in string mybadfilesource
        Console.Clear();
        Console.WriteLine("Where are your files located");
        Console.WriteLine(@"Example: D:\folder\subfolder\");
        string mybadfilesource = Console.ReadLine();

        //Ask user what character to remove and store value in string mychartodelete
        Console.WriteLine("What character do you want to remove");
        Console.WriteLine("Only 1 Character allowed");
        string mychartodelete = Console.ReadLine();

        //Ask user what character to replace mychartodelete with and store value in string mychartoreplace
        //if user just hits enter, mychartodelete will just be deleted
        Console.WriteLine("What character do you want to replace it with");
        Console.WriteLine("Press enter to just delete previously selected Character");
        Console.WriteLine("Only 1 Character allowed");
        string mychartoreplace = Console.ReadLine();


        try
        {
            //store list of files from mybadfilesource in var filelist
            var filelist = Directory.EnumerateFiles(mybadfilesource);
            foreach (string file in filelist)
                {
                    //renames the files by Replacing mychartodelete with mychartoreplace
                    var newfile = string.Format("{0}{1}",Path.GetFileNameWithoutExtension(file).Replace(mychartodelete, mychartoreplace),Path.GetExtension(file));
                    File.Move(file, Path.Combine(mybadfilesource, newfile));
                }
        }
        //Error Checking Process - Prints error message
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        //tell user the process is done and return to Main Menu
        Console.WriteLine("Finished - Press Enter to Return to Main Menu");
        Console.ReadLine();
        Console.Clear(); 
        Main();
    }

谢谢大家的帮助

这里有很多错误:

  1. 您正在错误的变量上调用替换
  2. 如果使用正确的变量,在foreach循环中修改变量仍然会出错
  3. 实际上并没有重命名任何内容,也没有将任何内容重新应用到实际文件中。

尝试这个:

 foreach (var file in Directory.EnumerateFiles(mybadfilesource))
 {
     var newfile = string.Format("{0}{1}",
            Path.GetFileNameWithoutExtension(file).Replace(mychartodelete, mychartoreplace),
            Path.GetExtension(file));
     File.Move(file, Path.Combine(mybadfilesource, newfile));
 }

请确保仅获取不带路径或扩展名的文件名,否则您也将更改它们

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM