Hello,
The following first reads all people, search for a particular person, if found change part of their phone number and writes people back to the original file.
If say one of the lines per person is not correct in any way you need to deal with that.
Code sample expects people.txt
in the executable folder
Ken
Sánchez
697-555-0142
Terri
Duffy
819-555-0175
Roberto
Tamburello
212-555-0187
Rob
Walters
612-555-0100
Gail
Erickson
849-555-0139
Jossef
Goldberg
122-555-0189
Person class has Contents property for writing data back to the file.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Contents => $"{FirstName}\n{LastName}\n{Phone}";
public override string ToString() => $"{FirstName} {LastName} {Phone}";
}
File operations
public class FileOperations
{
public static string _fileName = "people.txt";
/// <summary>
/// Write people back to same file as read from
/// </summary>
/// <param name="peopleList">valid list of <seealso cref="Person"/></param>
public static void Write(List<Person> peopleList)
{
File.WriteAllLines(_fileName, peopleList
.Select(item => item.Contents)
.ToArray());
}
/// <summary>
/// Assumes file exists and there are three line per person
/// </summary>
/// <returns>List of <see cref="Person"/></returns>
public static List<Person> Read()
{
var contents = File.ReadAllLines(_fileName);
string[][] chunks = contents
.Select((line, index) => new
{
Value = line,
Index = index
})
.GroupBy(x => x.Index / 3)
.Select(grp =>
grp.Select(x => x.Value).ToArray())
.ToArray();
return chunks.Select(item => new Person()
{
FirstName = item[0],
LastName = item[1],
Phone = item[2]
}).ToList();
}
}
Read file, search for person, change, save to the original file
class Program
{
static void Main(string[] args)
{
var peopleList = FileOperations.Read();
var person = peopleList.FirstOrDefault(p => p.FirstName == "Roberto" && p.LastName == "Tamburello");
if (person is not null)
{
person.Phone = "303-555-0187";
}
FileOperations.Write(peopleList);
}
}