C# 如何删除目录中每个文件的文件名中间字符 如何删除目录中每个文件名中间的字符?
我的目录中充满了诸如“Example01.1234312232.txt”、“Example02.23482343324.txt”等文件 我想删除“.1234312232”,这样它将命名为“Example01.txt”,并对目录中的每个文件执行此操作C# 如何删除目录中每个文件的文件名中间字符 如何删除目录中每个文件名中间的字符?,c#,C#,我的目录中充满了诸如“Example01.1234312232.txt”、“Example02.23482343324.txt”等文件 我想删除“.1234312232”,这样它将命名为“Example01.txt”,并对目录中的每个文件执行此操作 每个文件名中的字符数始终相同。最简单的方法是使用正则表达式替换 \.\d+ 对于空字符串“”: 这是一个你可以使用的 string fileNameOnly = Path.GetFileNameWithoutExtension(path); str
每个文件名中的字符数始终相同。最简单的方法是使用正则表达式替换
\.\d+
对于空字符串“”
:
这是一个你可以使用的
string fileNameOnly = Path.GetFileNameWithoutExtension(path);
string newFileName = string.Format("{0}{1}",
fileNameOnly.Split('.')[0],
Path.GetExtension(path));
值得一提的是,目录重命名问题的完整代码:
foreach (string file in Directory.GetFiles(folder))
{
string fileNameOnly = Path.GetFileNameWithoutExtension(file);
string newFileName = string.Format("{0}{1}",
fileNameOnly.Split('.')[0],
Path.GetExtension(file));
File.Move(file, Path.Combine(folder, newFileName));
}
您必须使用类和函数来获取文件列表。循环所有文件,并执行一次操作以获取所需字符串。
然后调用重命名文件。使用以下命令:
filename.Replace(filename.Substring(9, 15), ".txt")
您可以硬编码索引和长度,因为您说过字符数具有相同的长度。使用Directory.EnumerateFiles枚举文件,使用Regex.Replace获取新名称和文件。移动以重命名文件:
using System.IO;
using System.Text.RegularExpressions;
class SampleSolution
{
public static void Main()
{
var path = @"C:\YourDirectory";
foreach (string fileName in Directory.EnumerateFiles(path))
{
string changedName = Regex.Replace(fileName, @"\.\d+", string.Empty);
if (fileName != changedName)
{
File.Move(fileName, changedName);
}
}
}
}
我试过了,没有添加txt,它就删除了.txt,将其保留为“文件”,拆分可能会删除。txt@CSharpStudent:你看过“演示”链接了吗?我正在拆分没有扩展名的文件名,然后使用
Path.GetExtension
将其添加到新文件名中。如果要创建完整路径(即复制文件),则需要将完整路径与目录一起添加。因此,您应该使用Path.Combine
。尝试该程序,console.Writeline返回example1,或者您可以将格式更改为:string.format(“{0}.txt”@CSharpStudent:嗯,您的路径不是文件的有效路径。对于您的代码,您需要使用变量file
,而不是path
@CSharpStudent:我想为OP留下一些工作,但现在我已经提供了其余的,请看上面。
using System.IO;
using System.Text.RegularExpressions;
class SampleSolution
{
public static void Main()
{
var path = @"C:\YourDirectory";
foreach (string fileName in Directory.EnumerateFiles(path))
{
string changedName = Regex.Replace(fileName, @"\.\d+", string.Empty);
if (fileName != changedName)
{
File.Move(fileName, changedName);
}
}
}
}