Group
File Handling in C#
Objective
1. The user is asked to input the name of the text file they want to process.
2. The program reads the content of the file.
3. Every lowercase letter in the content is converted to uppercase.
4. The program then saves the transformed text to a new file with the ".uppercase" extension.
5. Proper error handling should be included for situations where the file cannot be found or read.
Write a program to read a file (of any kind) and dump its content to another file, changing the lowercase letters to uppercase.
Example C# Exercise
Show C# Code
using System;
using System.IO;
class TextFileUppercase
{
// Main method to execute the program
static void Main(string[] args)
{
// Ask the user for the input file name
Console.WriteLine("Please enter the name of the file to read:");
// Read the name of the input file from the user
string inputFileName = Console.ReadLine();
// Generate the name of the output file by appending ".uppercase"
string outputFileName = Path.GetFileNameWithoutExtension(inputFileName) + ".uppercase" + Path.GetExtension(inputFileName);
try
{
// Read all content from the input file
string content = File.ReadAllText(inputFileName);
// Convert all characters to uppercase
string upperCaseContent = content.ToUpper();
// Write the uppercase content to the output file
File.WriteAllText(outputFileName, upperCaseContent);
// Notify the user that the operation was successful
Console.WriteLine($"The content has been successfully saved to {outputFileName}");
}
catch (FileNotFoundException)
{
// If the file is not found, inform the user
Console.WriteLine("Error: The specified file could not be found.");
}
catch (Exception ex)
{
// Handle any other unexpected errors
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
Output
//If the input file data.txt contains:
this is a simple example of text content.
//The output file data.uppercase.txt will contain:
THIS IS A SIMPLE EXAMPLE OF TEXT CONTENT.