Tuesday 15 July 2014

Get latest File from a folder in SSIS

Sample code do the following:

  • Reads file from a Folder
  • Identifies the latest file
  • Rename the file and assign it to a variable

     try
            {
                var directory = new DirectoryInfo(Dts.Variables["User::SourceFolderPath"].Value.ToString());

                FileInfo[] files = directory.GetFiles();
                DateTime fileModifiedDate = DateTime.MinValue;

                foreach (FileInfo file in files)
                {
                    if (file.LastWriteTime > fileModifiedDate)
                    {
                        fileModifiedDate = file.LastWriteTime;
                        Dts.Variables["User::SourceFileName"].Value = file.ToString();
                    }

                }

                string oldFilePath = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + Dts.Variables["User::SourceFileName"].Value.ToString(); // Full path of old file
                string newFilePath = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + fileModifiedDate.Date.ToString("MM.dd.yyyy") + "_"
                                                                                               + Dts.Variables["User::SourceFileName"].Value.ToString(); // Full path of new file
                                  if
(Dts.Variables["User::SourceFileName"].Value.ToString().StartsWith(fileModifiedDate.Date.ToString("MM.dd.yyyy")) == false)
                    {
                        File.Move(oldFilePath, newFilePath);    //Raname file, if it donot start with latest fileCreateDate
                        Dts.Variables["User::SourceFileName"].Value = fileModifiedDate.Date.ToString("MM.dd.yyyy") + "_" + Dts.Variables["User::SourceFileName"].Value.ToString();
                    }
               
                Dts.TaskResult = (int)ScriptResults.Success;
            }
            catch (Exception ex)
            {  
                //Unlock variables
                if (Dts.Variables.Locked == true)
                {
                    Dts.Variables.Unlock();
                }
                //An error occurred.
                Dts.Events.FireError(0, "Error occured", ex.Message, String.Empty, 0);
                Dts.TaskResult = (int)ScriptResults.Failure;
            }

No comments:

Post a Comment