29. Removing blank lines

The following RemoveBlankLines method removes the blank lines from a file:

// Remove the empty lines from the indicated file.
private void RemoveBlankLines(string filename, out int numBlankLines,
out int numNonBlankLines)
{
// Read the file.
string[] lines = File.ReadAllLines(filename);
int totalLines = lines.Length;

// Remove blank lines.
List<string> nonblankLines = new List<string>();
foreach (string line in lines)
if (line.Trim().Length > 0)
nonblankLines.Add(line);

// Write the processed file.
numNonBlankLines = nonblankLines.Count;
numBlankLines = totalLines - numNonBlankLines;
File.WriteAllLines(filename, nonblankLines.ToArray());
}

This method uses the File class's ReadAllLines method to read the file's lines into an array of strings. It then creates a list to hold nonblank lines and loops through the array of lines.

The code calls each line's Trim method to remove whitespace from the line's ends. If the result is not blank, the code adds the original, non-trimmed line to the nonblank line list.

The Trim method returns a copy of a string with whitespace removed from its ends; it does not modify the original string. That's important in this example so that the trimmed line isn't added to the nonblank lines list.

After it has processed all of the file's lines, the method calculates the number of blank and nonblank lines in the original file and writes the nonblank lines back into the original file.

Download the RemoveBlankLines example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.218.19