question

palum avatar image
palum asked

Delete 6 months .csv old files from archive

I have csv files in archive with file names StudentInfo2012_02_14(YYYY_MM_DD). I want to delete all the files which are 6 months old.Below my code,which can delete a file which names todays date how can i delete a file which is 6 months old.I do not want to use the file system task. I want to do it using a script task and also want to delete only files of specific names like StudentInfo. public void main() { string StudentInfo = @"StudentInfo"; string SDay =DateTime.Now.Day.ToString().PadLeft(2,'0'); string SMonth = DateTime.Now.Month.ToString().PadLeft(2,'0'); string SYear = DateTime.Now.Year.ToString(); string ttime = SYear + "_" + SMonth + "_" + SDay; string[] ArcFiles = System.IO.Directory.GetFiles(directoryPath,StudentInfo + ttime + ".csv"); foreach(string filecr in arcFiles) { FileInfo crfilecr = new FileInfo(filecr); crfilecr.Delete(); } Dts.TaskResult = (int)ScriptResults.Success; }
ssisscript
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

eric.lynes avatar image
eric.lynes answered
First, you're doing a lot of string manipulation just to find something that can be done with `string ttime = DateTime.Now.ToString("yyyy_MM_dd") + ".csv"`. Now in order to get the file name from 6 months ago, just do `string ttime = DateTime.Now.AddMonths(-6).ToString("yyyy_MM_dd") + ".csv";` and repeat your `GetFiles` call and your `foreach`, or write that out as a method call, if you don't like copy and pasting code.
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

ThomasRushton avatar image
ThomasRushton answered
What I would do is test the File Object's DateCreated property. I've had to do similar stuff when scripting my way around an issue in SQL 2005 RTM - check my blog post for a vbs script that should be easily adapted to suit your requirements: http://thelonedba.wordpress.com/2010/10/18/sql-server-2005-rtm-maintenance-cleanup-fail/ This might be a VBS starting point for you, except you're not using VBScript... :-) Sorry! Dim oFS, oFile, oFolder Set oFS = CreateObject("Scripting.FileSystemObject") Set oFolder = oFS.GetFolder(directoryPath) For Each oFile in myFolder.Files If UCase(oFile.Name, 11) = UCase("StudentInfo") And UCase(Right(oFile.Name, 4)) = UCase(".csv") Then ' Name is OK to delete If oFile.DateCreated < Now-183 Then 'half a year, assuming leap year. 'Or 184 for the longest six months (Jul-Dec) 'Or you might want to do it properly... oFile.Delete End If End If Next
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.