Chris Tsiakoulas
Chris Tsiakoulas

Reputation: 186

C# file line remove with arraylist

I am trying to make a class which will help me delete one specific line from a file. So I came up with the idea to put all lines in an arraylist, remove from the list the line i don't need, wipe clear my .txt file and write back the remaining objects of the list. My problem is that I encounter some sort of logical error i can't fint, that doesn't remove the line from the arraylist and writes it back again. Here's my code:

public class delete
{
    public void removeline(string line_to_delete)
    {
        string[] lines = File.ReadAllLines("database.txt");
        ArrayList list = new ArrayList(lines);
        list.Remove(line_to_delete);
        File.WriteAllText("database.txt", String.Empty);
        using (var writer = new StreamWriter("database.txt"))
        {
            foreach (object k in lines)
            {
                writer.WriteLine(k);
            }
        }
    }
}

What is that I am missing? I tried lots of things on removing a line from a text file that did not work. I tried this because it has the least file operations so far.

Thanks!

Upvotes: 0

Views: 224

Answers (2)

Greg
Greg

Reputation: 11478

I believe you're intending:

public static void RemoveLine(string line)
{
     var document = File.ReadAllLines("...");
     document.Remove(line);
     document.WriteAllLines("..");
}

That would physically remove the line from the collection. Another approach would be to simply filter out that line with Linq:

var filter = document.Where(l => String.Compare(l, line, true) == 0);

You could do the Remove in an ArrayList proper documentation on how is here. Your code should actually work, all of these answers are more semantic oriented. The issue could be due to actual data, could you provide a sample? I can't reproduce with your code.

Upvotes: 0

Habib
Habib

Reputation: 223402

You can do:

var line_to_delete = "line to delete";
var lines = File.ReadAllLines("database.txt");
File.WriteAllLines("database.txt", lines.Where(line => line != line_to_delete));

File.WriteAllLines will overwrite the existing file.

Do not use ArrayList, there is a generic alternative List<T>. Your code is failing due to the use of ArrayList as it can only remove a single line matching the criteria. With List<T> you can use RemoveAll to remove all the lines matching criteria.

If you want to do the comparison with ignore case you can do:

File.WriteAllLines("database.txt", lines.Where(line => 
            !String.Equals(line, line_to_delete, StringComparison.InvariantCultureIgnoreCase)));

Upvotes: 4

Related Questions