如果名称包含一些文本,如何重命名某个文件夹中的文件标题

本文关键字:文件夹 标题 文件 重命名 包含一 文本 如果 | 更新日期: 2023-09-27 18:31:05

我在项目中有一个用于上传文件的文件夹,我想检查此文件夹中是否存在标题中包含一些文本的文件。如果文件包含文本"test",我想重命名文件

例如,在文件夹"/uploadedFiles/"中,我有 4 个文件:test_01.jpg,02.jpg,03.png,test_04.txt

我想重命名文件:"test_01.jpg"到"01.jpg"和"test_04.txt"到"04.txt"

我可以像这样编辑文件:

System.IO.File.Move("test_01.jpg", "test_01.jpg".Replace("test_",""));

我需要从此文件夹中获取标题中包含"test"的文件列表

如果名称包含一些文本,如何重命名某个文件夹中的文件标题

您可以获取名称中包含 test 的列表文件:

var files = Directory.EnumerateFiles(folderPath, "*test*.*");

您也可以使用正则表达式来执行此操作:

Regex reg = new Regex(@".*test.*'..*",RegexOptions.IgnoreCase);
var files = Directory.GetFiles(yourPath, "*.*")
                     .Where(path => reg.IsMatch(path))
                     .ToList();

这将为您提供匹配文件的列表,然后移动每个文件:

foreach (var file in Directory.EnumerateFiles("somePath", "test_*"))
{
    var newFileName = Path.GetFileName(file).Remove(0, 5);  // removes "test_"
    File.Move(file, Path.Combine(Path.GetDirectoryName(file), newFileName));
}
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(folderPathToUploadedFiles);
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
IEnumerable<System.IO.FileInfo> fullfileinfo =(from file in fileList  where file.Name.Contains("test") select file);

此代码使用关键字"test_"重命名所有文件。 由于"ToLower()"调用,它不区分大小写

        const string testKeyword = "test_";
        var testFilePaths = Directory.GetFiles(@"c:'tmp").Where(f => f.ToLower().Contains(testKeyword.ToLower()));
        foreach (var testFilePath in testFilePaths)
        {
            File.Move(testFilePath, testFilePath.Replace(testKeyword, string.Empty));
        }