我有一个文件列表
1_test.pdf、2_test.pdf、3_test.pdf、4_test.pdf、5_test.pdf、6_test.pdf、7_test.pdf、8_test.pdf、9_test.pdf 10_test.pdf。
我需要将它们重命名为格式
test_f0001.pdf、test_f0002.pdf、test_f0003.pdf、test_f0004.pdf、test_f0005.pdf、test_f0006.pdf、test_f0007.pdf、test_f0008.pdf、test_f0009.pdf、test_f0010.pdf。
是否可以在不复制或移动文件的情况下重命名它们? 谢谢!
当涉及到文件时,没有"重命名"这样的事情,你必须使用移动。
所以,简单地说,
var file = @"A.txt";
File.Move(file, "A1.txt");
将您的A.txt
重命名为A1.txt
.
编辑
要重命名文件,您可以操作字符串。假设您的原始文件符合您的示例:
var file = "10_test.pdf";
int.TryParse(file.Split('_').ToList().ElementAt(0), out int num);
var rename = string.Format("test_f{0:0000}.pdf", num);
所以这会改变
10_test.pdf ==> test_f0010.pdf
和
1_test.pdf==> test_f0001.pdf
string.Format()
中的{0:0000}
告诉它打印一个数字,用最多 4 位数字的前导零填充它。
您可以使用System.IO.File.Move
重命名文件,方法是将其移动到具有新名称的同一目录(重命名文件时,从技术上讲,您正在更改文件的完整路径(。
例如:
private static void CustomRename(string directoryPath)
{
foreach (var file in Directory.GetFiles(directoryPath))
{
var basePath = Path.GetDirectoryName(file);
var ext = Path.GetExtension(file);
// If it doesn't have our extension, continue
if (!ext.Equals(".pdf", StringComparison.OrdinalIgnoreCase)) continue;
var nameParts = Path.GetFileNameWithoutExtension(file).Split('_');
// If it doesn't have our required parts, continue
if (nameParts.Length != 2) continue;
var numericPart = nameParts[0];
int number;
// If the numeric part isn't numeric, continue
if (!int.TryParse(numericPart, out number)) continue;
// Create new file name and rename file by moving it
var newName = $"{nameParts[1]}_f{number:0000}{ext}";
File.Move(file, Path.Combine(basePath, newName));
}
}
不。您需要移动它:
System.IO.File.Move(oldNameFullPath, newNameFullPath);