我有一个小实用程序我写的是让用户从用户选择的特定目录中用文件名替换另一个字符。 我们的想法是让用户替换" _"或者他们想要的任何其他角色与他们想要的任何其他角色或完全删除它。
编辑:在从我的回复中学到的信息和一些谷歌搜索了解这些命令是如何工作之后,我想出了这段代码。任何反馈都会很好。
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();
}
谢谢大家的帮助
答案 0 :(得分:2)
这里有很多错误:
- 您正在使用错误的变量
调用替换- 如果使用正确的变量,在foreach循环中修改变量仍然会出错
- 你不是真的重命名任何东西,你没有将任何东西应用回实际文件。
醇>
试试这个:
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));
}
确保只获取没有路径或扩展名的文件名,否则你也会改变它们