0
My problem is this. I have several . txt files in a pc directory. These files have information on each line and have blank lines.
What I would need to do is read all the files in the directory, open them one by one, read the information in each, and add a numerical index in each, followed by a semicolon and erasing the blank or spaced lines.
Voilà, I got it partially.
My program reads the directory, lists the files, opens and reads the information in them, but when it goes to record the information, it replicates the information from the first file in the second.
Ex.: If in a file I have the provision
joao
legal
the result in the first file is
0;joao
1;legal
in the second file I have the information:
marcelo
medeiros
but, after running the program, the result in the second file is:
0;joao
1;legal
2;marcelo
3;medeiros
So, if there are many and many files, you can imagine what the final file would look like.
Can someone help me find where the bug in my program is?
Follows the code:
static void Main(string[] args)
{
List<string> lines = new List<string>();
string path3;
int counter = 0;
path3 = @"C:\Users\msant\Desktop\New folder\";
string[] files = Directory.GetFiles(path3);
foreach (var file in files)
{
if (File.Exists(file))
{
try
{
//ABRE E LÊ O ARQUIVO TXT
using (StreamReader reader = new StreamReader(file))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (!string.IsNullOrWhiteSpace(line))
{
var lineOutput = counter++ + ";";
lines.Add(lineOutput + line);
}
}
reader.Close();
reader.Dispose();
}
foreach (var line in lines)
{
Console.WriteLine(line);
}
//ESCREVE NOS ARQUIVOS TXT
using (StreamWriter writer = new StreamWriter(file))
{
foreach (var item in lines)
{
writer.WriteLine(item);
}
writer.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
}
}
else
{
Console.WriteLine("ALERTA: O ARQUIVO LOCALIZADO EM <-- " + path3+ " --> NAO EXISTE.");
}
Console.ReadKey();
}
}
Thanks for the option! Very elegant ;)
– Marcelo Medeiros dos Santos