批量将匹配文件名的文件移动到 C# 中的文件夹或使用脚本
Batch Moving files matching filenames to folders in C# or using a script
我想知道是否有人可以帮助或指出正确的方向来移动文件,其中文件名的一部分需要与文件夹名的一部分相匹配,例如:
将文件名 Cust-10598.txt 移动到名为 John-Doe-10598 的文件夹中这可能吗?
我能够在包含所有文件的根目录中创建所有文件夹,现在我想对它们进行排序并将它们分别放入匹配的文件夹中。
非常感谢任何帮助或想法
如果命名约定如此简单,您可以简单地在“-”上使用 Split()。
class Program
{
static void Main(string[] args)
{
var file = "Cust-10598.txt";
var fileSplit = file.Split('-');
var sourceDir = @"C:\";
var destFolder = "{name of destination folder}-" + Path.GetFileNameWithoutExtension(fileSplit[1]);
var destPath = @"C:\newpath";
File.Move(Path.Combine(source, file), Path.Combine(destPath, destFolder, file));
}
}
假设您已经使用 Directory.GetDirectores(),
获得了可能的文件夹列表
var listOfFolders = Directory.GetDirectories(basePath);
您可以使用以下方法找到给定文件名的关联文件夹。
string GetAssociatedDirectory(string fileName,IEnumerable<string> folderNames)
{
Regex regEx = new Regex(@"Cust-(?<Id>[\d]*)",RegexOptions.Compiled);
Match match = regEx.Match(fileName);
if (match.Success)
{
var customerId = match.Groups["Id"].Value;
if(folderNames.Any(folder=>folder.EndsWith($"-{customerId}")))
{
return folderNames.First(folder=>folder.EndsWith(customerId));
}
else
{
throw new Exception("Folder not found");
}
}
throw new Exception("Invalid File Name");
}
然后您可以使用File.Move将文件复制到目标目录
我想知道是否有人可以帮助或指出正确的方向来移动文件,其中文件名的一部分需要与文件夹名的一部分相匹配,例如:
将文件名 Cust-10598.txt 移动到名为 John-Doe-10598 的文件夹中这可能吗?
我能够在包含所有文件的根目录中创建所有文件夹,现在我想对它们进行排序并将它们分别放入匹配的文件夹中。
非常感谢任何帮助或想法
如果命名约定如此简单,您可以简单地在“-”上使用 Split()。
class Program
{
static void Main(string[] args)
{
var file = "Cust-10598.txt";
var fileSplit = file.Split('-');
var sourceDir = @"C:\";
var destFolder = "{name of destination folder}-" + Path.GetFileNameWithoutExtension(fileSplit[1]);
var destPath = @"C:\newpath";
File.Move(Path.Combine(source, file), Path.Combine(destPath, destFolder, file));
}
}
假设您已经使用 Directory.GetDirectores(),
获得了可能的文件夹列表var listOfFolders = Directory.GetDirectories(basePath);
您可以使用以下方法找到给定文件名的关联文件夹。
string GetAssociatedDirectory(string fileName,IEnumerable<string> folderNames)
{
Regex regEx = new Regex(@"Cust-(?<Id>[\d]*)",RegexOptions.Compiled);
Match match = regEx.Match(fileName);
if (match.Success)
{
var customerId = match.Groups["Id"].Value;
if(folderNames.Any(folder=>folder.EndsWith($"-{customerId}")))
{
return folderNames.First(folder=>folder.EndsWith(customerId));
}
else
{
throw new Exception("Folder not found");
}
}
throw new Exception("Invalid File Name");
}
然后您可以使用File.Move将文件复制到目标目录