使用SSIS和脚本组件移动文件

我需要在SSIS中的脚本组件中编写一个代码,将代码文件移动到相应的文件夹中。 我得到的文件通常被命名,例如“Dem323_04265.45.23.4”,“Dem65_459.452.56”,“Ec2345_456.156.7894”,我需要将它们移动到相应的文件夹。 我的文件夹的名称是“Oklahoma City(323)”,“New York(65)”..我需要将这些文件移动到匹配的文件夹,例如“Dem323_04265.45.23.4”将转到文件夹“Oklahoma City” (323)”。 我需要修改我的代码,使位于前两个或三个字母和下划线之间的数字匹配位于括号中的数字。 我已经做了好几天了,而且我是ssis和c#的新手,所以任何帮助都会受到赞赏。 这是我到目前为止的代码:

public void Main() { string filename; // string datepart; bool FolderExistFlg; filename = Dts.Variables["User::FileName"].Value.ToString(); // datepart = (filename.Substring(filename.Length - 12)).Substring(0, 8); var folderNumber = Regex.Match( filename, //Dts.Variables["OutputMainFolder"].Value.ToString(), @"\(([^)]*)\)").Groups[1].Value; FolderExistFlg = Directory.Exists(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + folderNumber); if (!FolderExistFlg) { Directory.CreateDirectory(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + folderNumber); } File.Move(Dts.Variables["SourceFolder"].Value.ToString() + "\\" + filename + "\\" + folderNumber, Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + filename); Dts.TaskResult = (int)ScriptResults.Success; } #region ScriptResults declaration enum ScriptResults { Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success, Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure }; #endregion } 

}

在这里,下面的代码片段将根据匹配条件移动文件。 您需要根据您的配置来处理源输入。

  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); } } }