How to I search and change a line in a text file in c#

2021-06-13T04:08:34.013+00:00

I am wanting to search for a person and change there interest in the file via user input then print it out to the console.

public static void List_Contestants()
{
Console.Clear();
Contestants[] Person = new Contestants[45];

        StreamReader File = new StreamReader(@"C:\Users\tom\OneDrive - Otago Polytechnic\Desktop\DealOrNoDeal.txt");
        int pos = 0;
        while (!File.EndOfStream)
        {
            Person[pos].First_Name = File.ReadLine();
            Person[pos].Last_Name = File.ReadLine();        //making it so we can distinguish between First name last name and Intrest
            Person[pos].Interests = File.ReadLine();
            pos++;
        }

        foreach (var contestants in Person)
        {
            Console.WriteLine(contestants.Last_Name);  //Write out The Last Names of eveyone with on the file.
        }
    }
Developer technologies | C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-06-13T11:59:38.427+00:00

    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);
    
        }
    }
    
    0 comments No comments

  2. Jack J Jun 25,296 Reputation points
    2021-06-14T02:43:57.15+00:00

    Hi @Thomas McIver-Chave (1000102302) ,

    You can refer to the following code to search the txt and change a line in a text file based on your input.

    I recommend that you use List to store information.

    class Program  
    {  
        static void Main(string[] args)  
        {  
            List<Person> list = new List<Person>();  
            string[] lines = File.ReadAllLines(@"test.txt");  
            for (int i = 0; i < lines.Count()/3; i++)  
            {  
                if(lines[i * 3]!=string.Empty|| lines[i * 3+1] != string.Empty|| lines[i * 3 + 1]!=string.Empty)  
                {  
                    list.Add(new Person { FistName = lines[i * 3], LastName = lines[i * 3 + 1], Interests = lines[i * 3 + 2] });  
                }  
            }  
            Console.WriteLine("Please input FirstName");  
            string firstname = Console.ReadLine();  
            Console.WriteLine("Please input LastName");  
            string lastname = Console.ReadLine();  
            Person p = list.Where(i => i.FistName == firstname && i.LastName == lastname).FirstOrDefault();  
            if (p == null)  
            {  
                Console.WriteLine("Please input the correct firstname and lastname");  
            }  
            else  
            {  
                Console.WriteLine("Please input modified Intersts");  
                string interst = Console.ReadLine();  
                p.Interests = interst;  
                File.Delete(@"test.txt");  
                foreach (var item in list)  
                {  
                    File.AppendAllLines(@"test.txt", new string[] { item.FistName, item.LastName, item.Interests });  
                }  
            }  
             
        }  
    }  
    
    public class Person  
    {  
        public string FistName { get; set; }  
    
        public string LastName { get; set; }  
    
        public string Interests { get; set; }  
    
    
    }  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.