delete files older than 30 days

Hi all,

Can VB delete files from a directory older than 30 days Or, is VB unnecessary for this simple task I was unable to find a way to do this with DOS.



Answer this question

delete files older than 30 days

  • Teymur Hajiyev

    It will be based on the create date and filename. The filename is yyyy/mm/dd.bak.
  • MrJavaGuy

    indeed it can be done. In the System.IO namespace there exists a File class (which has a method called Delete()) and also a FileInfo class. you can get the file information of a file and check to see its creation time for example and from that, if its more than 30 days old from the current date, then delete.

    Example:

    Dim theFiles() as String = System.IO.Directory.GetFiles("path")

    for each currentFile as String in theFiles

       Dim theFileInfo as new System.IO.FileInfo(currentFile)

       if theFileInfo.CreationTime ConditionHere then

          System.IO.File.Delete(currentFile)

       end if

    next

     

    does this help It depends on what you want to base your "older than 30 days"

     

    you could try this

    Dim theFiles() as String = System.IO.Directory.GetFiles("path")

    for each currentFile as String in theFiles

       Dim theFileInfo as new System.IO.FileInfo(currentFile)

       Dim dateDiff as TimeSpan = DateTime.Now.Subtract(theFileInfo.CreationTime.Date)

       if dateDiff.Days >= 30 then

          System.IO.File.Delete(currentFile)

       end if

    next



  • LAE2

    ive just modified my post for the last example. That should give you the days difference between now and the creation date of the file in question. If its more than or equal to 30 days it will remove it

  • delete files older than 30 days