I create a program that uses a txt file that looks like this:
01/11 09:56,yeo,no,110222100,no
01/11 09:55,Test,Test2,110222100,Test2
01/11 09:52,Jack,Jean,112222100,Jean
31/10 23:17,Rayane,Jean,111220000,Rayane
I would then like a line in this file to delete it, so I use this code:
for (int i = 0; i < lignes.Count; i++)
{
string ligne = lignes[i];
List<string> element = ligne.Split(',').ToList();
if (element.Contains(selectionDate[1])) //Ici on à les éléments de la ligne séléctionner
{
string ligneAr = null;
lignes[i] = ligneAr;
File.WriteAllLines(path, lignes);
}
}
But, when I use this code, this is what happens in the txt file:
01/11 09:56,yeo,no,110222100,no
01/11 09:55,Test,Test2,110222100,Test2
01/11 09:52,Jack,Jean,112222100,Jean
31/10 23:17,Rayane,Jean,111220000,Rayane
// Empty line
31/10 22:30,Rayane,André,122120101,Rayane
There's a hole in the text instead. How can I delete this hole? The code that allows you to create it is in the if()
Thank you.
Hole which you mentioned in your question is added due to assigning null
to lignes[i]
i.e lignes[i] = ligneAr;
. File.WriteAllLines()
inside for loop, is also wrong place to update your file.
No need to split your string lignes[i]
, you can just use .Where()
clause with required condition to get filtered result and write it to the file.
Something like,
var result = lignes.Where(ligne => !ligne.Contains(selectionDate[1]));
File.WriteAllLines(path, result);