Finding and removing items from a text file?

Scott George 21 Reputation points
2021-04-19T15:11:33.743+00:00

Hey guys, I've built a program that adding info to a text file. Its user database for a record collection, it can add band's info to a text file, but I want to let the user search for and remove band's info if the user sells the band's record. Not sure how to go about this. I'm watching the C# course videos, but thought I could get some other input about other ways of going about it.
here is my current code:
https://github.com/tsgxcode/OMDB/blob/master/Progarm.cs

Thanks :)

.NET Standard
.NET Standard
A formal specification of .NET APIs that are available on multiple .NET implementations.
483 questions
No comments
{count} votes

Accepted answer
  1. Xingyu Zhao-MSFT 5,341 Reputation points
    2021-04-20T06:19:51.387+00:00

    Hi @Scott George ,
    In order to correctly save the data into your text file, you need to change

        File.AppendAllText(@"C:\Users\TSG\source\repos\tsgxcode\OMDB\Data.txt",  
                ("{0}", ".", "{1}", ".", "{2}", ".", "{3}", ".", "{4}", ".",  
                 "{5}", ".", "{6}", ".") + Environment.NewLine);  
    

    To

     File.AppendAllText(@"test.txt",$"{artist}.{formationDate}.{favoriteAlbum}.{yearOfRelease}.{numberOfSongs}.{genre}" + Environment.NewLine);  
    

    Then, you can refer to the following code to removing the certain line from a text file.

            public static void removeArtist()  
            {  
                Console.Write("Please enter the artist name you want to delete: ");  
                string name = Console.ReadLine();  
                List<string> lst = File.ReadAllLines("Data.txt").Where(arg => !string.IsNullOrWhiteSpace(arg)).ToList();  
                lst.RemoveAll(x => x.Split('.')[0].Equals(name));  
                File.WriteAllLines("Data.txt", lst);  
            }  
    

    Hope it could be helpful.

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful