Need Help

  • Hi ,

    I am trying to delete files in a folder except the last created file in the folder.

    can you please help me with the logic.

    The files in the folder are sql server audit files with the extension .sqlaudit

    I cannot choose the files based on date because if the auditing data is not present on todays date . the old files can be deleted.

    I am looking for a logic which should look at the files in the folder and delete all the files in that folder except the last created file in that folder.

    I am using SQL Server 2008 R2 Enterprise edition RTM 64 bit on windows server 2008 R2 Enterprise edition sp1 64 bit

    Thank You,

  • In a script component, do something like this (untested): -

    DirectoryInfo directory = new DirectoryInfo("T:\\Test");

    FileInfo[] fileList = directory.GetFiles("*.*", SearchOption.AllDirectories);

    foreach (FileInfo file in fileList.Where(file => file != fileList.OrderByDescending(currentFile => currentFile.CreationTime).First()))

    {

    file.Delete();

    }


    Forever trying to learn
    My blog - http://www.cadavre.co.uk/
    For better, quicker answers on T-SQL questions, click on the following...http://www.sqlservercentral.com/articles/Best+Practices/61537/
    For better, quicker answers on SQL Server performance related questions, click on the following...http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply