重构:计算给定文件夹下所有文件的总行数

本文关键字:文件 计算 文件夹 重构 | 更新日期: 2023-09-27 18:18:46

我编写了一个代码来计算给定文件夹中所有文件的行数。它工作得很好,但我正在尝试包含所有可能的c#特性,以便将其重构为更紧凑、更高效的代码。请帮帮我。

代码如下:

    class LineNumberCounter
{
    public static string Calculate(string folderPath, string pattern = "*.txt")
    {
        DirectoryInfo dirInfo = new DirectoryInfo(folderPath.Trim());
        if (!dirInfo.Exists)
            throw new ArgumentException("No such directory exists");
        StringBuilder returnValue = new StringBuilder();
        long totalLines = 0;
        pattern.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).All(filter =>
        {
            int count = 0;
            dirInfo.GetFiles(filter.Trim(), 
                SearchOption.AllDirectories).All(file =>
                {
                    using (StreamReader reader = file.OpenText())
                    {
                        for (; reader.Peek() > -1; count++)
                            reader.ReadLine();
                    }
                    returnValue.AppendLine(string.Format("Number of lines with {0} pattern is {1}",
                        filter, count));
                    totalLines += count;
                    return true;
                }
            );
            return true;
        });
        //foreach (string filter in
        //    pattern.Split(new char[] { ';' },
        //        StringSplitOptions.RemoveEmptyEntries))
        //{
        //    FileInfo[] files = dirInfo.GetFiles(filter.Trim(),
        //        SearchOption.AllDirectories);
        //    int count = 0;
        //    Array.ForEach<FileInfo>(files, file =>
        //    {
        //        using (StreamReader reader = file.OpenText())
        //        {
        //            for (; reader.Peek() > -1; count++)
        //                reader.ReadLine();
        //        }
        //    });
        //    returnValue.AppendLine(string.Format("Number of lines with {0} pattern is {1}",
        //        filter, count));
        //    totalLines += count;
        //}
        returnValue.AppendLine();
        returnValue.AppendLine("Total Lines = " + totalLines);
        return returnValue.ToString();
    }
}

注释行是我最初写的。我尝试重构它。但是仍然想检查它是否有更多的作用域

重构:计算给定文件夹下所有文件的总行数

使用新的>=.NET 4方法File.ReadLines()

int total = File.GetFiles(folderPath, pattern)
                .Sum(x => File.ReadLines(x).Count());

来自MSDN的一些考虑:

ReadLines和ReadAllLines方法的区别如下ReadLines中,您可以在前面开始枚举字符串集合返回整个集合;当您使用ReadAllLines时,必须等待整个字符串数组返回,然后才能访问数组。因此,当你处理非常大的文件时,ReadLines可以更高效

foreach (var filePath in Directory.GetFiles(folderPath, pattern(//standard pattern), SearchOption.AllDirectories))
{
    var count=File.OpenText(filePath).ReadAllLines().Count();
    returnValue.AppendLine(string.Format("Number of lines with {0} pattern is {1}",
            Path.GetExtension(filePath), count));
}