I was able to merge several text files from the same directory into a final text file, grouping the same codes and summing their respective amounts, using the following code (credits to friend Vitor Mendes):
Dictionary<string, int> valores = new Dictionary<string, int>();
string diretorio = @"C:\teste";
string[] listaDeArquivos = Directory.GetFiles(diretorio);
if (listaDeArquivos.Length > 0)
{
string caminhoArquivoDestino = @"C:\teste\saida.txt";
FileStream arquivoDestino = File.Open(caminhoArquivoDestino, FileMode.OpenOrCreate);
arquivoDestino.Close();
List<string> linhasDestino = new List<string>();
foreach (string caminhoArquivo in listaDeArquivos)
{
foreach (var linhaArquivoAtual in File.ReadAllLines(caminhoArquivo))
{
string id = linhaArquivoAtual.Substring(0, linhaArquivoAtual.Length - 3);
string quantidade = linhaArquivoAtual.Substring(linhaArquivoAtual.Length - 3, 3);
if (valores.ContainsKey(id))
valores[id] = valores[id] + Convert.ToInt32(quantidade);
else
valores.Add(id, Convert.ToInt32(quantidade));
}
}
File.WriteAllLines(caminhoArquivoDestino, valores.Select(x => x.Key + x.Valeu.ToString("000")).ToArray());
}
The first line of the home text file contains 2 point-separated identification parameters. I'll illustrate:
Conteúdo do Arq1.txt
000032;30032014
123456010
654321020
Conteúdo do Arq2.txt
000032;30032014
123456005
654321005
Conteúdo do Arq3.txt
000033;23052014
123456050
654321020
Conteúdo do Arq4.txt
000033;23052014
123456020
654321005
Conteúdo do Arq5.txt
000033;20052014
123456001
654321002
Conteúdo do Arq6.txt
000033;20052014
123456009
654321008
When grouping these files, the program should generate different final files according to the parameters of the first line. In these sample files, the end result will be the following files:
ArqFinal00003320052014.txt
123456010
654321010
ArqFinal00003323052014.txt
123456070
654321025
ArqFinal00003230032014.txt
123456015
654321025
That is, the program should group the files according to the first line, creating different final files.