I adapted to previous answer for this case. I haven’t thought of all the possibilities. You have not given criteria to solve file malformation problems, if there is how to validate the codes and what happens if the quantity does not contain a valid numerical value.
I considered it implicit that the values of the quantity are always integers and that an invalid value would be considered zero. I also considered that the minimum a line should have of validation is the exact size of 9 characters.
I used an auxiliary data structure to put in memory all the codes through unique keys and adding the quantities in the existing codes.
I did a quick test and is presenting the expected result. The code can certainly be better organized.
Comments are being used only for didactic purposes and do not reflect my coding style.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
public class MergeFiles {
public static void Main(string[] args) {
var caminhoOrigem = @"C:\teste";
var nomeArquivoCompleto = @"C:\teste\saida.txt";
var itens = new Dictionary<string, int>(); //Cria a estrutura que permite chaves únicas do tipo string e valores associados do tipo int
int resultado;
foreach (var arquivo in Directory.GetFiles(caminhoOrigem, "*.txt")) { //Pega todos os arquivos com extensão txt disponíveis no diretório
if (arquivo != nomeArquivoCompleto) { //Não deixa processar o próprio arquivo que está sendo criado
foreach (var linha in File.ReadAllLines(arquivo)) { //Lê todas as linhas individualmente de cada arquivo
if (linha.Length == 9) { //Garante que a linha tem 9 caracteres
var chave = linha.Substring(0, 6); //Pega os 6 primeiros caracteres
var valor = (int.TryParse(linha.Substring(6, 3), out resultado) ? resultado : 0); //Pega os 3 caracteres seguintes e converte para numérico
if (itens.ContainsKey(chave)) { //verifica se já existe a chave no dicionário
itens[chave] = itens[chave] + valor; //adiciona o valor obtido na linha à chave já existe no dicionário
} else {
itens.Add(chave, valor); //Adiciona uma nova chave ainda inexistente no dicionário
}
}
}
}
}
//Cria o arquivo destino adicionando todas as linhas do dicionário recriando a mesma estrutura anterior através do LINQ
File.WriteAllLines(nomeArquivoCompleto, itens.Select(item => item.Key + item.Value.ToString("000")).ToArray());
}
}
I put in the Github for future reference.
You know regular expressions?
– Leonel Sanches da Silva
Hello Gypsy. I don’t know, but because you mentioned I started researching. I can already separate and identify the fields, in theory.
– Vhox
If all numbers are aligned, just use substring splitting, in a very simple way and without the need for regex.
– Bacco
@Bacco yes, they are "aligned", that is, the number of characters in the code field will always be 6 (the first six) and the number of characters in the code field will always be 3 (the last three). I’ll search the division.
– Vhox
@Vhox is really a case for substring. You can store the 6-digit ID as a key in an array, and add up the values in this array. I’m just not gonna venture into writing the code because I don’t use C#.
– Bacco
@DBX8 without knowing the language details, I would extract ID and QTD, and do something like this: if index ID does not exist in the array, it creates the ID input with QTD value, otherwise it adds QTD to the value of the existing ID. after reading all txts, it would generate the output. This approach would only be problematic if the txts were gigantic.
– Bacco
I thank you all. This is very difficult for me, but I will keep trying. If you have suggestions and help, you are more than welcome. Abs!
– Vhox