-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathListing05.21.CountingLinesGivenADirectory.cs
More file actions
71 lines (63 loc) · 1.75 KB
/
Listing05.21.CountingLinesGivenADirectory.cs
File metadata and controls
71 lines (63 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter05.Listing05_21;
#region INCLUDE
using System.IO;
public static class LineCounter
{
// Use the first argument as the directory
// to search, or default to the current directory
public static void Main(string[] args)
{
int totalLineCount = 0;
string directory;
if(args.Length > 0)
{
directory = args[0];
}
else
{
directory = Directory.GetCurrentDirectory();
}
totalLineCount = DirectoryCountLines(directory);
Console.WriteLine(totalLineCount);
}
#region HIGHLIGHT
static int DirectoryCountLines(string directory)
#endregion HIGHLIGHT
{
int lineCount = 0;
foreach(string file in
Directory.GetFiles(directory, "*.cs"))
{
lineCount += CountLines(file);
}
foreach(string subdirectory in
Directory.GetDirectories(directory))
{
#region HIGHLIGHT
lineCount += DirectoryCountLines(subdirectory);
#endregion HIGHLIGHT
}
return lineCount;
}
private static int CountLines(string file)
{
string? line;
int lineCount = 0;
// This can be improved with a using statement
// which is not yet described.
FileStream stream = new(file, FileMode.Open);
StreamReader reader = new(stream);
line = reader.ReadLine();
while(line != null)
{
if(line.Trim() != "")
{
lineCount++;
}
line = reader.ReadLine();
}
reader.Dispose(); // Automatically closes the stream
return lineCount;
}
}
#endregion INCLUDE