Solved

Delete files in a folder older than N days

Posted on 2004-10-28
1,787 Views
Last Modified: 2012-08-13
public void DeleteFilesFromFolder(string Folder_Path, int Days_Old)
{
//nav to folder path (Folder_Path passed in....must support both C:\  path  as well as UNC paths)
//delete all files older than Days_Old (passed in)
}


Please provide the source code for this function.  I don't do enough FSO to know how to do this fast.

I will research this on my own....if I win I'll request to PAQ the question....
0
Question by:knowlton
    14 Comments
     
    LVL 5

    Author Comment

    by:knowlton
    A beginning:

    public void DeleteFilesFromFolder(string Folder_Path, int Days_Old)
                      {
                            foreach (string s in Directory.GetFiles(Folder_Path))
                            {
                                  File.Delete(s);
                            }
                      }
    0
     
    LVL 5

    Author Comment

    by:knowlton
    I just need a way to determine the age of the files now.
    0
     
    LVL 2

    Assisted Solution

    by:tdisessa
         File oThisDir = new File(Folder_Path);

          File [] aFilesInDir = oThisDir.listFiles();

          for (int iFile = 0; iFile < aFilesInDir.length; iFile++)
          {
             if (aFilesInDir[iFile].lastModified() + 1000 * 60 * 60 * 24 < System.currentTimeMillis())
             {
                aFilesInDir[iFile].delete();
             }
          }  
    0
     
    LVL 2

    Expert Comment

    by:tdisessa
    My solution is in Java.  What language are you using?
    0
     
    LVL 5

    Author Comment

    by:knowlton
    Sorry...C#.  :)
    0
     
    LVL 2

    Expert Comment

    by:tdisessa
    It started out looking like Java.
    0
     
    LVL 2

    Expert Comment

    by:tdisessa
    Oh well.  :)
    0
     
    LVL 85

    Expert Comment

    by:Mike Tomlinson
    This is in VB.Net but you should be able to convert it easily:

        Private Sub DeleteFilesFromFolder(ByVal Folder_Path As String, ByVal Days_Old As Integer)
            If Directory.Exists(Folder_Path) Then
                Dim fileAge As TimeSpan
                Dim fi As FileInfo
                Dim file As String
                Dim files() As String = Directory.GetFiles(Folder_Path)
                For Each file In files
                    fi = New FileInfo(file)
                    fileAge = DateTime.Now().Subtract(fi.CreationTime)
                    If fileAge.Days > Days_Old Then
                        Try
                            fi.Delete()
                        Catch ex As Exception
                            MessageBox.Show(Folder_Path, "Delete Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        End Try
                    End If
                Next
            Else
                MessageBox.Show(Folder_Path, "Path Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        End Sub
    0
     
    LVL 85

    Expert Comment

    by:Mike Tomlinson
    If you don't want to use the creation date, then you can use either the last access or last write time:

        fileAge = DateTime.Now().Subtract(fi.LastAccessTime)
        fileAge = DateTime.Now().Subtract(fi.LastWriteTime)

    ~IM
    0
     
    LVL 5

    Author Comment

    by:knowlton
    what is fileage............ the difference in days?
    0
     
    LVL 85

    Expert Comment

    by:Mike Tomlinson
    fileAge is an instance of the TimeSpan class, which represents the time spanned between two Date objects:

        Dim fileAge As TimeSpan
        fileAge = DateTime.Now().Subtract(fi.CreationTime)

    You can get the time spanned in

        Ticks
        Milliseconds
        Seconds
        Mintutes
        Hours
        Days

    Using the properties in the TimeSpan class.

    ~IM
    0
     
    LVL 5

    Author Comment

    by:knowlton
    Please help debug:


    public void DeleteFilesFromFolder(string Folder_Path, int Days_Old)
                      {
                            foreach (string s in Directory.GetFiles(Folder_Path))
                            {
                                  System.DateTime dt = File.GetCreationTime(s);
                                  System.TimeSpan ts = System.DateTime.Now.Subtract(dt);

                                  double date_diff = ts.Days;

                                  if(date_diff >= Days_Old)
                                  {
                                        File.Delete(s);
                                  }
                            }
                      }


    date_diff does not seem correct....says 0 when the days should be like 120 + days difference!
    0
     
    LVL 85

    Accepted Solution

    by:
    Not sure what's going on there.  It's working on my system with this:

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            If FolderBrowserDialog1.ShowDialog = DialogResult.OK Then
                DeleteFilesFromFolder(FolderBrowserDialog1.SelectedPath, 10)
            End If
        End Sub

        Private Sub DeleteFilesFromFolder(ByVal Folder_Path As String, ByVal Days_Old As Integer)
            If Directory.Exists(Folder_Path) Then
                Dim s As String
                Dim dt As DateTime
                Dim ts As TimeSpan
                Dim date_diff As Double

                For Each s In Directory.GetFiles(Folder_Path)
                    dt = File.GetCreationTime(s)
                    ts = DateTime.Now().Subtract(dt)
                    date_diff = ts.Days

                    Debug.WriteLine(dt.ToString)
                    Debug.WriteLine(date_diff)
                Next
            Else
                MessageBox.Show(Folder_Path, "Path Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        End Sub
    0
     
    LVL 5

    Author Comment

    by:knowlton
    Turns out the file was hidden....I think that is why it wasn't working.

    Tom
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone. Privacy Policy Terms of Use

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    I know it’s not a new topic to discuss and it has lots of online contents already available over the net. But Then I thought it would be useful to this site’s visitors and can have online repository on vim most commonly used commands. This post h…
    If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
    In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
    In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

    875 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    12 Experts available now in Live!

    Get 1:1 Help Now