C# App: Exception Handling

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

    C# App: Exception Handling

    Hi All,

    Is it the right way of handling exception in a method?

    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;
            }
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    That looks like a pretty solid handling to me.

    Comment

    • Shani Aulakh
      New Member
      • Nov 2007
      • 44

      #3
      Thanks, But when i debug the application, the files get deleted but i dont see the msg showing Files successfully deleted.

      Comment

      • Shani Aulakh
        New Member
        • Nov 2007
        • 44

        #4
        can you check if this is coded properly 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 int DeleteFilesOlderThan(DateTime dt)
                {
                    string[] older = FilesOlderThan(dt);
                    int count = 0;
                    foreach (string file in files)
                    {
                        try
                        {
                            File.Delete(file.Name);
                            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;
                }
        
                public static string[] FilesOlderThan(DateTime dt)
                {
                    DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
                    FileInfo[] files = directory.GetFiles(FolderPath); //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 
                    }
                }

        Comment

        • Plater
          Recognized Expert Expert
          • Apr 2007
          • 7872

          #5
          Originally posted by Shani Aulakh
          Thanks, But when i debug the application, the files get deleted but i dont see the msg showing Files successfully deleted.
          Does it show the messages you print out in your catch {} block?

          Comment

          • Shani Aulakh
            New Member
            • Nov 2007
            • 44

            #6
            Before when i was compiling the application, it was showing in pending checkins that files successfully deleted. but not anymore:S

            Comment

            • Shani Aulakh
              New Member
              • Nov 2007
              • 44

              #7
              okay i did some modification in my class...but its not deleting specific files from event handler...
              [Code]
              using System;
              using System.IO;
              using System.Collecti ons;

              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

              public int DeleteFilesOlde rThan(int Days, int Hrs, int Mins, string filter)
              {
              DateTime dt = GetRelativeDate Time(Days, Hrs, Mins);
              ArrayList oldFilePaths = FilesOlderThan( dt, filter);
              int count = 0;
              foreach (string filePath in oldFilePaths)
              {
              try
              {
              File.Delete(fil ePath);
              count++;
              }
              catch (Exception e)
              {
              Console.WriteLi ne("Unable to delete {0}", filePath);
              Console.WriteLi ne("Reason: {0}", e);
              }
              Console.WriteLi ne("Files successfully deleted");
              }
              return count;
              }

              public static DateTime GetRelativeDate Time(int days, int hours, int minutes)
              {
              return DateTime.Now.Ad dDays(-days).AddHours(-hours).AddMinut es(-minutes);
              }

              public static ArrayList FilesOlderThan( DateTime dt, string filter)
              {
              DirectoryInfo directory = new DirectoryInfo(D irectory.GetCur rentDirectory() );
              FileInfo[] files = directory.GetFi les(filter); //get FileInfos for the files in the current directory matching the filter expression
              ArrayList older = new ArrayList(); //list to hold the result
              foreach (FileInfo file in files)
              {
              if (file.CreationT ime < dt) //if smaller (older) than the relative time
              older.Add(file. Name); //add it to the list
              }

              return older;
              }
              }
              }
              [Code]

              button event handler that deletes files..
              Code:
                      private void DeleteFiles_Click(object sender, EventArgs e)
                      {
                          FolderWatcher fw = new FolderWatcher();
                          fw.FolderPath = @"c:\csharp"; // FolderName
                          fw.DeleteFilesOlderThan(0, 0, 0, "*.txt"); // deletes everything older than specified days,hrs, and mins respectively 
                      }

              Comment

              • Plater
                Recognized Expert Expert
                • Apr 2007
                • 7872

                #8
                And you keep getting the exceptions printed out?

                Comment

                • Shani Aulakh
                  New Member
                  • Nov 2007
                  • 44

                  #9
                  nopes, I am not getting any exceptions printed out

                  Comment

                  • Plater
                    Recognized Expert Expert
                    • Apr 2007
                    • 7872

                    #10
                    Have you put a breakpoint on the File.Delete() to see if
                    A) it's actually getting called
                    and
                    B) What value is being passed to it?

                    Comment

                    • Shani Aulakh
                      New Member
                      • Nov 2007
                      • 44

                      #11
                      okay i will check that out.......i want to know another thing. I wrote the following code to create text files and to create multiple text files i guess i can run the code in a loop. but i want to generate dummy files using .txt, .log, .exe file format in button GenerateTestFil es eventhandler

                      Code:
                      using System;
                      using System.IO;
                      
                      class FileTest
                      {
                          static void Main()
                          {
                              StreamWriter outStream = null;
                              string filename = "output.txt";
                      
                              try
                              {
                                  outStream = new StreamWriter(filename);
                                  outStream.WriteLine("Hello World");
                                  outStream.Close();
                              }
                              catch (Exception e)
                              {
                                  Console.WriteLine("Unable to create file {0}", filename);
                                  Console.WriteLine("Reason: {0}", e);
                                  return;
                              }
                              Console.WriteLine("File successfully created");
                          }
                      }

                      Comment

                      • Shani Aulakh
                        New Member
                        • Nov 2007
                        • 44

                        #12
                        I created three textboxes to enter days, mins, hrs and a combo box for extension on my form.

                        this wouldn't work?
                        Code:
                                private void DeleteFiles_Click(object sender, EventArgs e)
                                {
                                    FolderWatcher fw = new FolderWatcher();
                                    fw.FolderPath = @"c:\csharp"; // FolderName
                                    OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
                                    fw.DeleteFilesOlderThan(int.Parse(Textbox1.Text), int.Parse(Textbox2.Text), int.Parse(Textbox3.Text), OpenFileDialog1.Filter); // deletes everything older than specified days,hrs, and mins respectively 
                                }

                        Comment

                        • Plater
                          Recognized Expert Expert
                          • Apr 2007
                          • 7872

                          #13
                          It might or it might not, did you go in and check to see if it even found any files that matched the search pattern?

                          Comment

                          • Shani Aulakh
                            New Member
                            • Nov 2007
                            • 44

                            #14
                            i put a breakpoint to check it throughly. this is the FolderWatcher.c s class. I modified the code using DateTime object. I think FolderPath is not defined in the current directory
                            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));
                                    //}
                            
                                    public int DeleteFilesOlderThan(int Days, int Hrs, int Mins, string filter)
                                    {
                                        DateTime dt = GetRelativeDateTime(Days, Hrs, Mins);
                                        ArrayList oldFilePaths = FilesOlderThan(dt, filter);
                                        int count = 0;
                                        foreach (string filePath in oldFilePaths)
                                        {
                                            try
                                            {
                                                File.Delete(filePath);
                                                count++;
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine("Unable to delete {0}", filePath);
                                                Console.WriteLine("Reason: {0}", e);
                                            }
                                            Console.WriteLine("Files successfully deleted");
                                        }
                                        return count;
                                    }
                            
                                    public static DateTime GetRelativeDateTime(int days, int hours, int minutes)
                                    {
                                        return DateTime.Now.AddDays(-days).AddHours(-hours).AddMinutes(-minutes);
                                    }
                            
                                    public static ArrayList FilesOlderThan(DateTime dt, string filter)
                                    {
                                        DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
                                        FileInfo[] files = directory.GetFiles(filter); //get FileInfos for the files in the current directory matching the filter expression
                                        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 
                                        }
                            
                                        return older;
                                    }
                                }
                            }

                            Comment

                            Working...