C#用更改的名称替换文件

本文关键字:替换 文件 | 更新日期: 2023-09-27 18:26:22

我正在尝试查找和替换文件,但是有点问题。这些文件的结构类似于PAVS_13001_0_I.pts。编号13001_0根据版本而变化。但是,我需要替换具有字符串PAVS_####_#_I.pts 的文件

请记住,有许多文件的名称不同,如PM_13001_0_I.ptsbuild.13.0.1.4.ClientOutput.zip等。这样的文件至少有15个。字符串应该匹配,但数字会改变。

如何替换数值发生更改的文件?

C#用更改的名称替换文件

如果它们都在同一目录中,您可以尝试枚举该目录中的文件,并将名称与正则表达式进行比较,如下所示:

string[] prefixes = {"PAVS", "PM"};
foreach (string filePath in Directory.EnumerateFiles(directory)
{
  foreach (string prefix in prefixes)
  {
    if (Regex.IsMatch(file, prefix + @"_'d+_'d+_I'.pts"))
    {
      //Move the file
    }
  }
}

开始:

//appSettings section:
//<add key="filename-patterns" value="PAVS_*_*_I.pts;omg.*.zip"/>
string[] patterns = ConfigurationManager.AppSettings["filename-patterns"].Split(';');
string sourceDir = @"C:'from'";
string destinationDir = @"C:'to'";
foreach (string pattern in patterns)
{
    IEnumerable<string> fileNames = Directory.EnumerateFiles(sourceDir, pattern, SearchOption.AllDirectories);
    fileNames.ToList().ForEach(x => File.Move(x, x.Replace(sourceDir, destinationDir)));
}

请注意,您可以将最后一个参数更改为SearchOption.AllDirectories并遍历所有树。但是,当移动到目标文件夹时,它将保持文件夹结构。

我在C:'from:上有这些文件

PAVS_123_1_I.pts
PAVS_123_2_I.pts
whatever.txt

它工作正常。

UPDATE:我修改了代码以使用多种模式。您可以将该列表保留在配置文件中,这样就不必为每个新的文件模式重新构建应用程序。

UPDATE:现在代码正在读取当前配置文件上的appSettings。只需记住添加对System.Configuration的引用即可。