Answer to Question #180522 in C# for Miley

Question #180522

Get all the files from a given directory and perform the following actions

1.       Return the number of text files in the directory (*.txt).

2.       Return the number of files per extension type.

3.       Return the top 5 largest files, along with their file size (use anonymous types).

4.       Return the file with maximum length


1
Expert's answer
2021-04-16T12:00:27-0400
using System;
using System.Linq;
using System.IO;
class Program
{
    static void Main(string[] args)
    {
        string path = @"F:\Directory";
        DirectoryInfo dir = new DirectoryInfo(path);
        FileInfo[] files = dir.GetFiles();


        Console.WriteLine("Return the number of text files in the directory (*.txt).");
        Console.WriteLine(".txt - " + GetCountFormat(".txt", files));


        Console.WriteLine("\nReturn the number of files per extension type.");
        GetFormats(files).ToList().ForEach(x => Console.WriteLine(x + " - " + GetCountFormat(x, files)));


        Console.WriteLine("\nReturn the top 5 largest files, along with their file size (use anonymous types).");
        GetCountBytes(files, 5).ToList().ForEach(x => Console.WriteLine(x.FullName));


        Console.WriteLine("\nReturn the file with maximum length.");
        GetCountBytes(files, 1).ToList().ForEach(x => Console.WriteLine(x.FullName));


        Console.ReadKey();
    }
    private static string[] GetFormats(FileInfo[] files)
    {
        return files.Where(x => x.FullName.Contains('.'))
                    .Select(x => x.FullName.Remove(0, x.FullName.IndexOf('.')))
                    .Distinct()
                    .ToArray();
    }
    private static int GetCountFormat(string format, FileInfo[] files)
    {
        if (format.Contains(".") == false)
            format = "." + format;
        return files.ToList()
                    .Where(x => x.FullName.Contains(format))
                    .Count();
    }
    private static FileInfo[] GetCountBytes(FileInfo[] files, int countsReceive = 1)
    {
        files = files.OrderBy(x => -x.Length)
                     .ToArray();
        FileInfo[] answer = new FileInfo[countsReceive];
        Array.Copy(files, 0, answer, 0, countsReceive);
        return answer;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS