Wednesday, July 31, 2019

Recursive Deletion of Folders & Files (C#)

Sometimes, there is situation when we have to delete nested folders and files through code. Here is an example to achieve the functionality.




        public static void RecursiveDelete(DirectoryInfo baseDir)
        {
            if (!baseDir.Exists)
                return;

            foreach (var dir in baseDir.EnumerateDirectories())
            {
                RecursiveDelete(dir);
            }
            var files = baseDir.GetFiles();
            foreach (var file in files)
            {
                file.IsReadOnly = false;
                file.Delete();
            }
            baseDir.Delete();
        }


Implementation:- Below is the implementation of the method.Here I had created another method, which takes the root folder path and the no. of months. The no. of months are used here to delete the folders which the older than these no. from today. For example:- if today is 30 July, 2019, and the no. of months passed is 2, then the new date is 27 May, 2019. It means this method will delete all the folders (and it's contents) for May 2019 month.



        public static bool DeleteFolder(string LogFolder, int months)
        {
            bool bSuccess = false;

            try
            {
                DirectoryInfo ObjDirectoryInWhichToSearch = new DirectoryInfo(LogFolder);
                DirectoryInfo[] ObjDirectoriesToDelete = ObjDirectoryInWhichToSearch.GetDirectories(DateTime.Now.AddMonths((-1) * months).ToString("yyyy-MM") + "*");

                foreach (DirectoryInfo ObjSingleDirectory in ObjDirectoriesToDelete)
                {
                    try
                    {
                        RecursiveDelete(ObjSingleDirectory);
                    }
                    catch (Exception ex) { }
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine("ERROR In DeleteFolder:- " + ex.Message);
            }
            finally
            {
            }
            return bSuccess;
        }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.