Program to search specified folder and its subfolders and write the folder’s content in the following format

C:\abc
  *.txt - 2 files
  *.xlsx - 1 file
    C:\abc\def
      *.csv  - 3 files
    C:\abc\ghi
      no files found
    C:\abc\jkl
       *.exe - 2 files
       C:\abc\jkl\mno
         *.dll - 1 file

C# Program

class Program
{
    //Global Variables

    static int pCount = 0;
   
    static StringBuilder sb = new StringBuilder(); // string which contains the actual output to write to the file

    //Main function

    static void Main(string[] args)
    {
        try
        {
            //Local variables

            string folderName = string.Empty;
           
            string fileName = string.Empty;
           
            bool flag = true;           

            
            Console.WriteLine("Please enter folder name to search :");

            ValidateFolder(ref folderName, flag);

            Console.WriteLine("Folder name : {0}", folderName);

            Console.WriteLine("Please enter file name :");

            ValidateFile(ref fileName, flag);

            Console.WriteLine("File name : {0}", fileName);

            pCount = folderName.Split('\\').Length; // variable to assign parent directory length split by '\'

            DirectorySearch(folderName); // search current and sub folders

            //Write output to the file

            string fileLocation = "C:\\" + fileName.Trim(); // output file location

            FileStream objFileStream = null;

            if (!File.Exists(fileLocation))
            {
                objFileStream = File.Create(fileLocation);
               
                objFileStream.Close();
            }

            StreamWriter objStreamWriter = new StreamWriter(fileLocation);

            objStreamWriter.Write(sb);
           
            objStreamWriter.Close();

            Console.WriteLine("Output file {0} created successfully in {1}.", fileName, fileLocation);           
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    //Function to search folders and sub folders

    public static void DirectorySearch(string directory)
    {
        try
        {
            Output(directory);

            foreach (var subdirectory in Directory.GetDirectories(directory))
            {
                DirectorySearch(subdirectory);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }   

    //Function to write actual output to a string

    public static void Output(string directory)
    {
        try
        {
            var objDirectoryInfo = new DirectoryInfo(directory);

            var iCount = (objDirectoryInfo.FullName.Split('\\').Length) - pCount; // variable to create tree view structure

            sb.AppendLine(new String(' ', iCount) + objDirectoryInfo.FullName);

            var Files = objDirectoryInfo.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly)
                                    .GroupBy(x => x.Extension)
                                    .Select(x => new { Extension = x.Key, Count = x.Count() })
                                    .ToList();

            if (Files.Count > 0)
            {
                foreach (var fg in Files) // fg - file group
                {
                    string formatString = "{2}" + " " + "*{0} - {1}";

                    sb.AppendLine(string.Format(formatString, fg.Extension, fg.Count, new String(' ', iCount + 1)));
                }
            }
            else
            {
                sb.AppendLine(new String(' ', iCount + 1) + "No files found");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }  

    //Function to validate the foleder name in the directory

    public static void ValidateFolder(ref string folderName, bool flag)
    {
        do
        {
            folderName = Console.ReadLine().Trim();

            if (string.IsNullOrEmpty(folderName))
            {
                flag = false;
            }
            else
            {
                flag = Regex.IsMatch(folderName, @"^(?:[a-zA-Z]\:|\\)(\\[\w\.$ ]+)+\\?$");
            }

            if (!flag)
            {
                Console.WriteLine(@"Folder name format: [a-zA-Z]:\[a-zA-Z0-9]\...");
            }
            else
            {
                flag = Directory.Exists(folderName);

                if (!flag)
                    Console.WriteLine(@"Folder doesn't exists in the directory.");
            }

        } while (!flag);
    }

    //Function to validate the output file name

    public static void ValidateFile(ref string fileName, bool flag)
    {
        do
        {
            fileName = Console.ReadLine().Trim();

            if (string.IsNullOrEmpty(fileName))
            {
                flag = false;
            }
            else
            {
                flag = Regex.IsMatch(fileName, @"^(?:[a-zA-Z0-9]+)+\.(?i)(txt)$");
            }

            if (!flag)
                Console.WriteLine("File name format: [a-zA-Z0-9].[txt]");

        } while (!flag);
    }   
}

No comments :

Post a Comment