
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Counting Lines of Text
|
577
array must be created and filled with RegexCompilationInfo objects. The next step is to
create the assembly in which the expression will live. An instance of the
AssemblyName
class is created using the default constructor. Next, this assembly is given a name (do
not include the
.dll file extension in the name; it is added automatically). Finally, the
CompileToAssembly method can be called with the RegexCompilationInfo array and the
AssemblyName object supplied as arguments.
In our example, this assembly is placed in the same directory that the
executable was launched from.
See Also
See the “.NET Framework Regular Expressions” and “AssemblyName Class” topics
in the MSDN documentation.
10.9 Counting Lines of Text
Problem
You need to count lines of text within a string or within a file.
Solution
Use the LineCount method shown in Example 10-8 to read in the entire file and count
the number of line feeds.
Example 10-8. LineCount method
using System;
using System.Text.RegularExpressions;
using System.IO;
public static long LineCount(string source, bool isFileName)
{
if (source != null)
{
string text = source;
if (isFileName)
{
using (FileStream FS = new FileStream(source, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
using (StreamReader SR = new StreamReader(FS))
{