Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C# Write a method called AddNameAndAge() that takes an string called filename

ID: 3774674 • Letter: I

Question

In C# Write a method called AddNameAndAge() that takes an string called filename as its only parameter, and that doesn't return a value. Your method must ask the user for their first name, their last name and their age on three separate lines in that order. And then your method must open up the file with the filename that was passed, and append the file by saving each of the three values on separate lines in that file in the same order given. When you save the values, save them on a line by themselves without any label in front of the value. Be sure to catch any Exception that is thrown during your reading in the values from the user and your saving the values to the file. And if you catch an Exception be sure to print the message that is connected to that Exception. You only have to write the method, not the entire class. public static void AddNameAndAge(string filename) { }

Explanation / Answer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.IO;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter the file name : ");
string input = Console.ReadLine();
AddNameAndAge(input);
}
  
public static void AddNameAndAge(string filename) {
string firstName;
string lastName;
int age = 0 ;
bool isNumeric=false;
try{
Console.WriteLine("Enter the first name : ");
firstName = Console.ReadLine();
Console.WriteLine("Enter the Last name : ");
lastName = Console.ReadLine();
do{
Console.WriteLine("Enter the Age : ");
string sAge = Console.ReadLine();
isNumeric = Int32.TryParse(sAge, out age);
}while(!isNumeric);
  
if(System.IO.File.Exists(filename)==true){
using (StreamWriter sw = File.AppendText(filename))
{
sw.WriteLine(firstName);
sw.WriteLine(lastName);
sw.WriteLine(age);
}  
  
}else{
Console.WriteLine("File Not exist!!!!!!");
Console.WriteLine("Creating the file with name : "+filename);
using (StreamWriter sw = File.CreateText(filename))
{
sw.WriteLine(firstName);
sw.WriteLine(lastName);
sw.WriteLine(age);
}
}
Console.WriteLine("Reading file : ");
int i = 0;
using (StreamReader sr = File.OpenText(filename))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if(i%3 == 0){
Console.WriteLine("First Name : "+s);
}
else if(i%3 == 1){
Console.WriteLine("Last Name : "+s);
}
else{
Console.WriteLine("Age : "+s);
}
i++;
}
}

}
catch (Exception e)
{
Console.WriteLine("Exception caught: ", e);
}
}
}
}