Objective
Create a C# program to count the amount of words stored in a text file
Write Your C# Exercise
C# Exercise Example
// Import the System namespace for basic functionality
using System;
// Import the IO namespace for file handling
using System.IO;
// Create the class to count words in the text file
class WordCounter
{
// Main method where the program starts
static void Main(string[] args)
{
// Ask the user for the path of the text file
Console.WriteLine("Enter the path of the text file:");
// Get the file path from the user
string filePath = Console.ReadLine();
// Start of try block to handle any file or reading errors
try
{
// Read the content of the file
string content = File.ReadAllText(filePath);
// Count the number of words in the file by splitting the content into words
int wordCount = CountWords(content);
// Display the result to the user
Console.WriteLine("The number of words in the file is: " + wordCount);
}
catch (Exception ex) // Catch any exceptions that may occur during file reading
{
// Print the exception message if an error occurs
Console.WriteLine("An error occurred: " + ex.Message);
}
}
// Method to count the number of words in a string
private static int CountWords(string content)
{
// Split the content by spaces, tabs, newlines, etc. to get an array of words
string[] words = content.Split(new char[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
// Return the length of the array, which is the number of words
return words.Length;
}
}
More C# Programming Exercises of File Management
Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.
This C# exercise involves creating a program to display the width and height of a BMP file using a BinaryReader. The program should read the BMP file header an...
This C# exercise involves creating a "Text to HTML converter". The program should read a source text file and create an HTML file from its contents. The destination f...
This C# exercise involves creating a program to "invert" a file using a FileStream. The program should create a file with the same name as the original file, b...
This C# exercise involves creating a program that reads a BMP file using a FileStream and displays its width and height. The BMP format has a spe...
This C# exercise involves creating a program that copies a source file to a destination file using a FileStream and a block size of 512 KB. The program should ...
This C# exercise is about the ID3 specifications, which apply to any file or audiovisual container, but are primarily used with audio containers. There are three comp...