0% found this document useful (0 votes)
12 views3 pages

File Handling and Exception Handling

file handlinf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views3 pages

File Handling and Exception Handling

file handlinf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

File Handling and Exception Handling

Code:

using System;

using System.IO;

class FileHandlingAssignment

static void Main()

string inputFile = "input.txt";

string outputFile = "output.txt";

try

if (!File.Exists(inputFile)) // Read data from the input file

throw new FileNotFoundException($"The file '{inputFile}' does not exist.");

string[] lines = File.ReadAllLines(inputFile);

Console.WriteLine("File read successfully. Processing data...");

// Perform a specified operation (e.g., counting the number of words in each line)

string[] results = ProcessData(lines);

File.WriteAllLines(outputFile, results); // Write results to the output file

Console.WriteLine($"Data processed successfully. Results written to '{outputFile}'.");

catch (FileNotFoundException ex)

Console.WriteLine($"Error: {ex.Message}");

LogError(ex);

catch (FormatException ex)


{

Console.WriteLine("Error: Invalid data in the file.");

LogError(ex);

catch (Exception ex)

Console.WriteLine("An unexpected error occurred.");

LogError(ex);

static string[] ProcessData(string[] lines) // Function to process data

string[] results = new string[lines.Length];

for (int i = 0; i < lines.Length; i++)

// Example operation: Count words in each line

int wordCount = lines[i].Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries).Length;

results[i] = $"Line {i + 1}: {wordCount} words";

return results;

static void LogError(Exception ex) // Function to log errors

string logFile = "error_log.txt";

string logMessage = $"[{DateTime.Now}] {ex.GetType()}: {ex.Message}\n{ex.StackTrace}\n";

File.AppendAllText(logFile, logMessage);

Console.WriteLine($"Error details logged to '{logFile}'.");

}
Explanation of the Code:

1. File Handling:

o Uses File.ReadAllLines to read all lines from the input file.

o Processes the data using a helper function (ProcessData).

o Writes results to the output file using File.WriteAllLines.

2. Exception Handling:

o FileNotFoundException: Thrown if the input file is missing.

o FormatException: Example for handling invalid data (extendable as needed).

o General Exception: Catches all other unforeseen errors.

3. Error Reporting:

o Displays meaningful error messages to the console.

o Logs detailed error information (timestamp, exception type, message, stack trace) to a
file (error_log.txt).

Example:

Input File (input.txt):

Hello world!

C# is fun to learn.

File handling is important.

Output file (output.txt):

Line 1: 2 words

Line 2: 5 words

Line 3: 4 words

Error Log (error_log.txt):

[2025-01-05 14:30:22] System.IO.FileNotFoundException: The file 'input.txt' does not exist.

at FileHandlingAssignment.Main()

You might also like