using System; using System.Collections.Generic; using System.Text; using System.IO; namespace PhoneBook { class FileIO { public string name; public string lastname; public string phone; //public FileIO(string _name, string _phone) //{ // name = _name; // phone = _phone; //} public void add() { StreamWriter fw = File.AppendText("phones.txt"); fw.WriteLine("Lastname: " + lastname + " " + "Name: " + name + " " + "Phone: " + phone); fw.Close(); } public string searchbyName() { string buffer = null; string RecordSearched = "Not Found"; int compareResult = 0; if(!(File.Exists("phones.txt"))) { RecordSearched = "Error no phone index."; } else { StreamReader fr = File.OpenText("phones.txt"); while ((buffer = fr.ReadLine()) != null) { string bufferNonspaced = buffer.Replace(" ", ""); if ((compareResult = (bufferNonspaced.IndexOf("Name:" + name))) != -1) { RecordSearched = buffer; break; } } fr.Close(); } return RecordSearched; } public string searchbyLastName() { string buffer = null; string RecordSearched = "Not Found"; int compareResult = 0; if (!(File.Exists("phones.txt"))) { RecordSearched = "Error no phone index."; } else { StreamReader fr = File.OpenText("phones.txt"); while ((buffer = fr.ReadLine()) != null) { string bufferNonspaced = buffer.Replace(" ", ""); if ((compareResult = (bufferNonspaced.IndexOf("Lastname:" + lastname))) != -1) { RecordSearched = buffer; break; } } fr.Close(); } return RecordSearched; } public string deletebyName() { string buffer = null; bool error = false; string RecordDeleted = "Not Found"; int compareResult = 0; if (!(File.Exists("phones.txt"))) { RecordDeleted = "No phone index"; error = true; } else { StreamWriter fw = new StreamWriter("temp.txt"); StreamReader fr = File.OpenText("phones.txt"); while ((buffer = fr.ReadLine()) != null) { string bufferNonspaced = buffer.Replace(" ", ""); if ((compareResult = (bufferNonspaced.IndexOf("Name:" + name))) != -1) { RecordDeleted = buffer; } else { fw.WriteLine(buffer); } } fr.Close(); fw.Close(); } File.Delete("phones.txt"); if (!error) { File.Move("temp.txt", "phones.txt"); } return RecordDeleted; } public string deletebyLastName() { string buffer = null; bool error = false; string RecordDeleted = "Not Found"; int compareResult = 0; if (!(File.Exists("phones.txt"))) { RecordDeleted = "No phone index"; error = true; } else { StreamWriter fw = new StreamWriter("temp.txt"); StreamReader fr = File.OpenText("phones.txt"); while ((buffer = fr.ReadLine()) != null) { string bufferNonSpaced = buffer.Replace(" ", ""); if ((compareResult = (bufferNonSpaced.IndexOf("Lastname:" + lastname))) != -1) { RecordDeleted = buffer; } else { fw.WriteLine(buffer); } } fr.Close(); fw.Close(); } File.Delete("phones.txt"); if (!error) { File.Move("temp.txt", "phones.txt"); } return RecordDeleted; } } }