Efficient way to delete a line from a text file

前端 未结 8 1903
暖寄归人
暖寄归人 2020-11-29 11:09

I need to delete a certain line from a text file. What is the most efficient way of doing this? File can be potentially large(over million records).

UPDATE: below is

8条回答
  •  借酒劲吻你
    2020-11-29 11:50

    The most straight forward way of doing this is probably the best, write the entire file out to a new file, writing all lines except the one(s) you don't want.

    Alternatively, open the file for random access.

    Read to the point where you want to "delete" the line. Skip past the line to delete, and read that number of bytes (including CR + LF - if necessary), write that number of bytes over the deleted line, advance both locations by that count of bytes and repeat until end of file.

    Hope this helps.

    EDIT - Now that I can see your code

    if (!_deletedLines.Contains(counter)) 
    {                            
        writer.WriteLine(reader.ReadLine());                        
    }
    

    Will not work, if its the line you don't want, you still want to read it, just not write it. The above code will neither read it or write it. The new file will be exactly the same as the old.

    You want something like

    string line = reader.ReadLine();
    if (!_deletedLines.Contains(counter)) 
    {                            
        writer.WriteLine(line);                        
    }
    

提交回复
热议问题