This is a C# Program to implement phonebook.
This C# Program Implements PhoneBook.
Reads a file with names and phone numbers and builds a phone book from it and Returns the phone number for a given name.
Here is source code to Implement PhoneBook.The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
/* * C# Program to Implement PhoneBook */ using System; using System.Collections; using System.IO; class PhoneBook { static void Main(string[] arg) { Hashtable tab = new Hashtable(); string fileName; if { (arg.Length > 0) fileName = arg[0]; } else { fileName = "phoneBook.txt"; } StreamReader r = File.OpenText(fileName); string line = r.ReadLine(); while (line != null) { int pos = line.IndexOf('='); string name = line.Substring(0, pos).Trim(); long phone = Convert.ToInt64(line.Substring(pos + 1)); tab[name] = phone; line = r.ReadLine(); } r.Close(); for (; ; ) { Console.Write("Name : "); string name = Console.ReadLine().Trim(); if (name == "") break; object phone = tab[name]; if (phone == null) Console.WriteLine("-- Not Found in Phone Book"); else Console.WriteLine(phone); } } }
In C# Program, we are reading a file with names and phone numbers and build a phone book from it and return the phone number for a given name. If else condition statement is used to assign the value of ‘arg[0]’ variable to the file name.
Otherwise, if the condition is false then execute the else statement. Assign the phonebook text file to the file name variable. While loop is used to check that line variable value is not equal to null. If the condition is true then execute the iteration of the loop. In substring() function assign the name, from the file present in read mode.
Using ToInt64() function convert the text in number format to the phone variable. Then close the file. If else condition statement, is used to display the name and phone number from the phone book.
Name : Ram 9999945670 Name : Raj -- Not Found in Phone Book
Sanfoundry Global Education & Learning Series – 1000 C# Programs.
- Check C# Books
- Practice MCA MCQs
- Check MCA Books
- Practice Computer Science MCQs
- Check Computer Science Books