The situation is this: I have a file, there are lines in it. I'm trying to find a string by its content and delete it. But the problem is that I can not find on the Internet how to remove it.
That is, the work of this method should be as follows:
The user enters a login, and the file is searched for, if it finds one, then it must delete this line.

The file itself:

lol:9cdfb439c7876e703e307864c9167a15 you:91c366db3df8b21eeb76be5c250f1a40 kek:4cfdc2e157eefe6facb983b1d557b3a1 wewe:2a7d544ccb742bd155e55c796de8e511 

Here is my code:

 public void DeleteUser() { var log = EnterLogin(); string path = ".htpasswd"; string[] deluser = System.IO.File.ReadAllLines(path, Encoding.Default); foreach (string items in deluser) { if (items.Contains(log)) { } } } 

    2 answers 2

    Text format - streaming, it is impossible to throw a part out of the middle.

    Read the file line by line, write only the necessary lines to the output (another!) File, then delete the original file and move the new file to the old position.


    An alternative method would be to read the file by byte, memorize the current read and write position, add the bytes through the encoder decoder to a string, check for the end of the line, possibly change the write position, and discard the tail at the end. Believe me, you do not want this.

    • As an option, read the file into memory, then search \ delete the required line in the loaded buffer (for example, read 4 kb each). In this case, it is natural to memorize with which - for which line of the source file we considered. If there is a required line in the buffer, then delete it from the buffer and write the buffer in place (you can not even write the entire fragment, but the changes themselves. In general, for such purposes it is better to use something suitable - json / xml, then such problems has arisen. - QuaternioNoir
    • @QuaternioNoir: Problem in parsing encoding. For example, for UTF-8, one character can consist of several bytes and cross the border of a four-kilobyte buffer. - VladD

    If you modify your code, you must do the following:

     public void DeleteUser() { var log = EnterLogin(); string path = ".htpasswd"; string[] deluser = System.IO.File.ReadAllLines(path, Encoding.Default); deluser = deluser.Where(line => line != log); System.IO.File.WriteAllLines(path, deluser, Encoding.Default); } 

    But in the case of a large file, this will be more costly than the solution proposed by VladD.