Constantin Mihaila
Constantin Mihaila

Reputation: 41

Delete a line form a text file

I need to delete a line from a text file. The problem is, when I try to delete a line, I have to press BtnStergeMedicam twice to delete. I don't know why I have to press it twice.

private void BtnStergeMedicam_Click(object sender, EventArgs e)
{
    string line;
    string line_to_delete = ListAfisMedicam.SelectedItem.ToString();//I take the line
    //to delete from ListAfisMedicam
    using (StreamReader reader = new StreamReader(@"D:\MyTest.txt"))
    {
        using (StreamWriter writer = new StreamWriter(@"D:\MyTest2.txt"))
        {
            while ((line = reader.ReadLine()) != null)
            {
                if (String.Compare(line, line_to_delete) == 0)
                    continue;
                writer.WriteLine(line);
            }
             writer.Close();
        }
         reader.Close();
    }
    System.IO.File.Copy(@"D:\MyTest2.txt", @"D:\MyTest.txt",true);
    ListAfisMedicam.Items.Clear();
    string[] lines = System.IO.File.ReadAllLines(@"D:\MyTest.txt");
    foreach (string linie in lines)
    {
        ListAfisMedicam.Items.Add(linie);
    }
}

Upvotes: 3

Views: 152

Answers (1)

Constantin Mihaila
Constantin Mihaila

Reputation: 41

I found the problem. ListAfisMedicam.SelectedItem.ToString() return me \nID - 01, Nume - Nurofen, Lot - 0123, Categorie - Capsula, Producator - Dona, Cantitate - 300, DataIntrare - 13-Jan-16 12:00:00 AM, DataFabricarii - 01-Jan-16 12:00:00 AM, DataExpirarii - 31-Jan-16 12:00:00 AM, PretVanzare - 2; and when It read each line and compare, It read like upper but w/o \n When I try second time( press the BtnStergeMedicam second time) ListAfisMedicam.SelectedItem.ToString() return ID - 01, Nume -Nurofen ...

Edit: Fix the problem. Thank you @tom_redox. The problem where somewhere else. When I populate list box I punt an \n and this was the problem. From now I will start use breakpoint everytime when I will got any problem

Upvotes: 1

Related Questions