I was wondering if someone could assist or point me in the right direction to move files where part of the filename needs to be matched to part of the foldername for example:
Moving filename Cust-10598.txt to a folder named John-Doe-10598 Is this possible?
I was able to create all the folders inside the root directory where all the files are contained, now I would like to sort them and put each of them inside the matching folder.
Any help or ideas are highly appreciated
Assuming you already have a list of probably folders using Directory.GetDirectores(),
var listOfFolders = Directory.GetDirectories(basePath);
You can find the associated Folder for given filename using following method.
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");
}
You can then use File.Move to copy the file to destination directory
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments