[c#] Delete specific line from a text file?

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 appreciated?

Related Questions

Efficient way to delete a line from a text file (C#)

This question is related to c# text-files

The answer is


You can actually use C# generics for this to make it real easy:

        var file = new List<string>(System.IO.File.ReadAllLines("C:\\path"));
        file.RemoveAt(12);
        File.WriteAllLines("C:\\path", file.ToArray());

The best way to do this is to open the file in text mode, read each line with ReadLine(), and then write it to a new file with WriteLine(), skipping the one line you want to delete.

There is no generic delete-a-line-from-file function, as far as I know.


One way to do it if the file is not very big is to load all the lines into an array:

string[] lines = File.ReadAllLines("filename.txt");
string[] newLines = RemoveUnnecessaryLine(lines);
File.WriteAllLines("filename.txt", newLines);

What? Use file open, seek position then stream erase line using null.

Gotch it? Simple,stream,no array that eat memory,fast.

This work on vb.. Example search line culture=id where culture are namevalue and id are value and we want to change it to culture=en

Fileopen(1, "text.ini")
dim line as string
dim currentpos as long
while true
    line = lineinput(1)
    dim namevalue() as string = split(line, "=")
    if namevalue(0) = "line name value that i want to edit" then
        currentpos = seek(1)
        fileclose()
        dim fs as filestream("test.ini", filemode.open)
        dim sw as streamwriter(fs)
        fs.seek(currentpos, seekorigin.begin)
        sw.write(null)
        sw.write(namevalue + "=" + newvalue)
        sw.close()
        fs.close()
        exit while
    end if
    msgbox("org ternate jua bisa, no line found")
end while

that's all..use #d


This can be done in three steps:

// 1. Read the content of the file
string[] readText = File.ReadAllLines(path);

// 2. Empty the file
File.WriteAllText(path, String.Empty);

// 3. Fill up again, but without the deleted line
using (StreamWriter writer = new StreamWriter(path))
{
    foreach (string s in readText)
    {
        if (!s.Equals(lineToBeRemoved))
        {
            writer.WriteLine(s);
        }
    }
}

  1. Read and remember each line

  2. Identify the one you want to get rid of

  3. Forget that one

  4. Write the rest back over the top of the file


Are you on a Unix operating system?

You can do this with the "sed" stream editor. Read the man page for "sed"


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);
    }

I cared about the file's original end line characters ("\n" or "\r\n") and wanted to maintain them in the output file (not overwrite them with what ever the current environment's char(s) are like the other answers appear to do). So I wrote my own method to read a line without removing the end line chars then used it in my DeleteLines method (I wanted the option to delete multiple lines, hence the use of a collection of line numbers to delete).

DeleteLines was implemented as a FileInfo extension and ReadLineKeepNewLineChars a StreamReader extension (but obviously you don't have to keep it that way).

public static class FileInfoExtensions
{
    public static FileInfo DeleteLines(this FileInfo source, ICollection<int> lineNumbers, string targetFilePath)
    {
        var lineCount = 1;

        using (var streamReader = new StreamReader(source.FullName))
        {
            using (var streamWriter = new StreamWriter(targetFilePath))
            {
                string line;

                while ((line = streamReader.ReadLineKeepNewLineChars()) != null)
                {
                    if (!lineNumbers.Contains(lineCount))
                    {
                        streamWriter.Write(line);
                    }

                    lineCount++;
                }
            }
        }

        return new FileInfo(targetFilePath);
    }
}

public static class StreamReaderExtensions
{
    private const char EndOfFile = '\uffff';

    /// <summary>
    /// Reads a line, similar to ReadLine method, but keeps any
    /// new line characters (e.g. "\r\n" or "\n").
    /// </summary>
    public static string ReadLineKeepNewLineChars(this StreamReader source)
    {
        if (source == null)
            throw new ArgumentNullException(nameof(source));

        char ch = (char)source.Read();

        if (ch == EndOfFile)
            return null;

        var sb = new StringBuilder();

        while (ch !=  EndOfFile)
        {
            sb.Append(ch);

            if (ch == '\n')
                break;

            ch = (char) source.Read();
        }

        return sb.ToString();
    }
}