question

ScottGeorge-6811 avatar image
0 Votes"
ScottGeorge-6811 asked ScottGeorge-6811 commented

Finding and removing items from a text file?

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 :)

dotnet-standard
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

XingyuZhao-MSFT avatar image
0 Votes"
XingyuZhao-MSFT answered ScottGeorge-6811 commented

Hi @ScottGeorge-6811 ,
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.



· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank! The first suggestion is much better then my original code.
The second for removing an item does not crash, but it does not actually ask to remove an artist. I'll probably just need to either write a new do/while loop for it? Or just in corporate it into the existing do/while?

Thanks again! :)

0 Votes 0 ·