C#: add/show delete method using date time object

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Shani Aulakh
    New Member
    • Nov 2007
    • 44

    C#: add/show delete method using date time object

    Hi there,

    I have a FolderWatcher.c s class that will monitor a given folder and delete files older than X number of days. I have the following methods. I need to add/show delete mothod using date time object.

    Code:
            public static DateTime GetRelativeDateTime(int days, int hours, int minutes)
            {
                return DateTime.Now.AddDays(-days).AddHours(-hours).AddMinutes(-minutes);
            }
    
            public static string[] FilesOlderThan(DateTime dt)
            {
                DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
                FileInfo[] files = directory.GetFiles(); //get FileInfos for the files in the current directory 
                ArrayList older = new ArrayList(); //list to hold the result 
                foreach (FileInfo file in files)
                {
                    if (file.CreationTime < dt) //if smaller (older) than the relative time 
                        older.Add(file.Name); //add it to the list 
                }
            }
    i want to know couple of other stuff as well..returning an array list instead of string[] is better or not? What is the difference between timespan object and DateTime object?..Are there any benefits of using timespan object instead of datetime object?

    Thanks in advance for the help!!
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    Either the FileInfo of File class (or both?) has a .Delete() function I believe, so you could just call that for each of your files that is too old.

    They are just as they sound DateTime represents a specific DateTime in real life(December 1st, 2006 3:45 AM), whereas a TimeSpan just represents an amount of time (42mins 36seconds).

    Comment

    • Shani Aulakh
      New Member
      • Nov 2007
      • 44

      #3
      would this work?

      Code:
              public int DeleteFilesOlderThan(int days, int hrs, int mins)
              {
                  string[] older = FilesOlderThan(Days, Hrs, Mins);
                  int count = 0;
                  foreach (string file in files)
                  {
                      try
                      {
                          File.Delete(file);
                          count++;
                      }
                      catch (Exception e)
                      {
                          Console.WriteLine("Unable to delete " + file);
                          Console.WriteLine("Reason: {0}", e);
                          //Console.WriteLine("Detected an exception!!!\n" + e );
                      }
                      Console.WriteLine("Files successfully deleted");
                  }
                  // presumably number of files deleted to be returned
                  return count;
              }

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        it looks like it should, assuming your function that finds old files is correct.
        does that string[] contain filenames like "C:\mydirectory \somefile.txt" or does it just contain "somefile.t xt", because I believe you will need a fully qualified path for it to work correctly.

        Comment

        • Shani Aulakh
          New Member
          • Nov 2007
          • 44

          #5
          I checked this peice of code using cosole application and it worked. I used a different coding method though. This is the class that monitors and deletes Files older than X number of days
          Code:
          using System;
          using System.IO;
          using System.Collections;
          
          namespace Files_ExtLib1
          {
              public class FolderWatcher
              {
                  string m_FolderPath;
          
                  public FolderWatcher()
                  {
                      //
                      // TODO: Add constructor logic here
                      //
                  }
          
                  #region Property
                  public string FolderPath
                  {
                      get
                      {
                          return m_FolderPath;
                      }
                      set
                      {
                          m_FolderPath = value;
                      }
                  }
                  #endregion
          
                  /// <summary>
                  /// Deletes the files older the days, hours, and
                  /// minutes specified
                  /// </summary>
                  /// <param name="Days"></param>
                  /// <param name="Hrs"></param>
                  /// <param name="Mins"></param>
                  /// <returns>Number of files deleted</returns>
                  public int DeleteFilesOlderThan(int Days, int Hrs, int Mins)
                  {
                      string[] oldFilePaths = FilesOlderThan(Days, Hrs, Mins);
                      int count = 0;
                      foreach (string filePath in oldFilePaths)
                      {
                          try
                          {
                              File.Delete(filePath);
                              count++;
                          }
                          catch (Exception e)
                          {
                              Console.WriteLine("Unable to delete " + filePath);
                              Console.WriteLine("Reason: {0}", e);
                              //Console.WriteLine("Detected an exception!!!\n" + e );
                          }
                          Console.WriteLine("Files successfully deleted");
                      }
                      // presumably number of files deleted to be returned
                      return count;
                  }
          
          
                  /// <summary>
                  /// Reurns filenames having last modified time older than
                  /// specified period.
                  /// </summary>
                  /// <param name="Days"></param>
                  /// <param name="Hrs"></param>
                  /// <param name="Mins"></param>
                  /// <returns></returns>
                  public string[] FilesOlderThan(int Days, int Hrs, int Mins)
                  {
                      TimeSpan ts = new TimeSpan(Days, Hrs, Mins, 0);
                      ArrayList oldFilePaths = new ArrayList();
                      // FolderPath is assumed to be path being watched
                      string[] filePaths = Directory.GetFiles(FolderPath);
                      DateTime currentDate = DateTime.Now;
                      foreach (string filePath in filePaths)
                      {
                          DateTime lastWriteDate = File.GetLastWriteTime(filePath);
                          if ((currentDate - lastWriteDate) > ts)
                          {
                              oldFilePaths.Add(filePath);
                          }
                      }
                      return (string[])oldFilePaths.ToArray(typeof(string));
                  }
              }
          }
          and it worked perfectly fine when i pass the parameters using command line arguments to the executable. I checked the FolderWatcher.c s class on a dummy folder.
          Code:
          static void Main(string[] args)
             {
                FolderWatcher fw = new FolderWatcher();
                fw.FolderPath = @"c:\my documents\temp"; // or whatever
                int days = int.Parse(args[0]);
                int hrs = int.Parse(args[1]);
                int mins = int.Parse(args[2]);
                fw.DeleteFilesOlderThan(days,hrs,mins);       
             }
          My colleague wanted me to do the whole procedue using DateTime object. So, I have created the two methods for that which I already included in my first post. I just want to know how do i create a DeleteFilesOlde rThan method using DateTime object. Is it possible to create method that can create test files with different format lets say .log, .txt, .exe and have another method to delete specific file type e.g delete .txt files only or .exe or .log
          I just want to add more functionality to FolderWatcher.c s class because I want to use it with prod where we deal with like 10,000 files at once and have to delete like 10 for example....
          Thanks for your time

          Comment

          • Plater
            Recognized Expert Expert
            • Apr 2007
            • 7872

            #6
            Well using the DateTime object you could just compare it against the the file datetime to see if it's older.
            So if you passed in a datetime object: {December 12th, 2006 12:51 AM} you would do your comparison with the passed in datetime object, INSTEAD of doing the .AddDays() etc.

            Directory.GetFi les(FolderPath) should also take a "pattern" argument that would allow you to do "*.txt" to only get filesnames that end in .txt

            Comment

            • Shani Aulakh
              New Member
              • Nov 2007
              • 44

              #7
              Are you only allowed to define one pattern? ie, "*.txt"? Or
              can you define multiple patterns? ie, "*.txt; *.exe; *.log"?

              Comment

              • Plater
                Recognized Expert Expert
                • Apr 2007
                • 7872

                #8
                Originally posted by Shani Aulakh
                Are you only allowed to define one pattern? ie, "*.txt"? Or
                can you define multiple patterns? ie, "*.txt; *.exe; *.log"?
                I *think* it's only one pattern.
                BUT, you could call it a bunch of times and keep joining them together.

                Comment

                Working...