I need to write a code in script component in SSIS that will move files to corresponding folders. Files that I\'m getting are usually named, for example \"Dem323_04265.45.23.4\"
Here you go, the below snippet would move the files as per the match criteria. You need to take care of the source input as per your configuration.
string filePath = @"C:\Packages\StackOverflow";
//string fileName = string.Empty;
//get list of files
string[] filePaths = Directory.GetFiles(filePath);
//get list of folders
string[] dirPaths = Directory.GetDirectories(filePath);
//loop through the files and move them
foreach(string fileNames in filePaths)
{
string[] pathArr = fileNames.Split('\\');
string fileName = pathArr.Last().ToString();
int index = fileName.IndexOf('_');
string fileNamePart = fileName.Substring(0, index);
//get the first numeric part of the filename to perform the match
var fileNameNumPart = Regex.Replace(fileNamePart, "[^0-9]", "");
//find related directory
var dirMatch = dirPaths.FirstOrDefault(stringToCheck => stringToCheck.Contains(fileNameNumPart.ToString()));
if (dirMatch != null)
{
// move would fail if file already exists in destination
if (!File.Exists(dirMatch + '\\' + fileName))
{
File.Move(fileNames, dirMatch + '\\' + fileName);
}
}
}