Delete specific line from a text file?

前端 未结 10 1666
既然无缘
既然无缘 2020-11-29 11:14

I need to delete an exact line from a text file but I cannot for the life of me workout how to go about doing this.

Any suggestions or examples would be greatly appr

10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 11:46

    No rocket scien code require .Hope this simple and short code will help.

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

    OR use this

    public void DeleteLinesFromFile(string strLineToDelete)
        {
            string strFilePath = "Provide the path of the text 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);
        }
    

提交回复
热议问题