-3

Greeting, I'm currently having some issues with System.IO text file. Currently I'm trying to remove a line in the text file but I do not know how to do it.

For Example:-

[1]26/6/2020 2:30:02 PM|5MB|That File ~

[2]26/6/2020 2:30:10 PM|5MB|That File ~

[3]26/6/2020 2:30:41 PM|5MB|That File ~

[4]26/6/2020 2:33:22 PM|5MB|That File ~

<I'm trying to remove the bold one, is it possible to remove it?>

  • What have you already tried to do yourself to get this done. Please include specific issues you've had with trying this rather than just asking "How do I do x" https://stackoverflow.com/help/how-to-ask. Have you done any research? Looked at this question and its answers for example https://stackoverflow.com/questions/668907/how-to-delete-a-line-from-a-text-file-in-c – Remy Jun 26 '20 at 06:45
  • Sorry about that, and thank you for pointing out the directions I need to go. – Guan Sheng Wong Jun 26 '20 at 07:00
  • What criteria are you using to determine which line to delete? Are you using the (presumably) line number inside brackets [] ? – Nathan Champion Jun 26 '20 at 07:05
  • Just a tip: you can't "remove" a line from a file as such. You have to modify the whole file in memory, then write it back to disk, or create a new file. That's why you never see sample code that simply removes a line from a file. – Captain Kenpachi Jun 26 '20 at 07:07
  • 1
    Is your question genuinely asking if it's _possible_ to make changes to a file? It's definitely possible! A very large number of applications rely on making changes to files. – ProgrammingLlama Jun 26 '20 at 07:23
  • Thank you for all the replies, now I understand how it works. Again, thank you. – Guan Sheng Wong Jun 26 '20 at 09:32

1 Answers1

2

Deleting Line at certain Index:

List linesList = File.ReadAllLines("myFile.txt").ToList();            
linesList.RemoveAt(1);
File.WriteAllLines("myFile.txt"), linesList.ToArray());

Deleting Line with certain Value:

public void DeleteLinesFromFile(string strLineToDelete)
    {
        string strFilePath = "Path to the file";
        string strSearchText = strLineToDelete;
        string strOldText;
        string n = "";
        StreamReader sr = File.OpenText(strFilePath);
        while ((strOldText = sr.ReadLine()) != null)
        {
            if (!strOldText.Contains(strSearchText))
            {
                n += strOldText + Environment.NewLine;
            }
        }
        sr.Close();
        File.WriteAllText(strFilePath, n);
    }
IndieGameDev
  • 2,905
  • 3
  • 16
  • 29
  • 2
    @CaptainKenpachi you wouldn't need to remove the old file ... just overwrite the existing one – derHugo Jun 26 '20 at 07:38