Read specific text inside a . txt in c#

Asked

Viewed 8,188 times

3

I need to read a text file that contains several lines:

1            C0000000000                       132008281               
06140214     080515                            0000000005990 
00000000000000000000000000000000000599000000000000000000000000000

I need to take only the amount 132008281 and put it into a variable, just that value.

I’m using the following code:

//cria uma lista para armazenar os dados encontrados no documento
List<string> dados = new List<string>();
// indica qual o caminho do documento
string filePath = CaminhoArquivo;
//declara uma variável para receber linha por linha do doc
string linha;
//verifica se existe um doc com o nome passado ates de fazer a leitura
if (File.Exists(filePath))
{
       //usa uma biblioteca chamada StreamReader para fazer a leitura do arquivo baseado no caminho informado
       using (StreamReader reader = new StreamReader(filePath))
       {
           //cria um loop para adicionar linha por linha do doc até sua ultima linha
           while ((linha = reader.ReadLine()) != null)
           {
               //adiciona linha a linha a nossa lista de dados
               dados.Add(linha);
           }
       }
       for (int i = 0; i < dados.Count; i++)
       {
           Leiturax += dados[i].ToString()+"\n";
       }   
       Leiturax = Leiturax;
}
else
{
       //caso não encontre nenhum registro da a mensagem abaixo
       MessageBox.Show("Nenhum registro encontrado!", "Lendo Arquivo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

This code creates a Array, But I just need to get that bit of text. Can someone help me?

  • 1

    Is there any pattern that is common in the snippet you want to pick up? you want to only take that value in the whole file?

2 answers

3


Follow the code to always search for the third value (separated by whitespace) of each line, and add to a list valoresEncontrados.

List<string> valoresEncontrados = new List<string>();

try
{
    string[] lst = File.ReadAllLines(filePath);

    foreach (var item in lst)
    {
        string[] linha = item.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        if (linha.Length >= 3)
        {
            valoresEncontrados.Add(linha[2]);
        }
    }
}
catch(Exception ex)
{

}
  • and if instead of using a list I use a Datatable. How would it look?

  • With Datatable it gets a little more complex, but you can take a look here, or convert a List to Datatable as here

0

I think the code is self-explanatory

using System.IO;
using System.Linq;

try
{
    var valores = File.ReadLines(filePath)
                      .Select(line => line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries))
                      .Where(split => split.Length >= 3)
                      .Select(split => split[2])
                      .ToList();

}
catch(IOException ex)
{
    //mostrar erro
}

Note: it is useless to check if the file exists with File.Exists before opening it, see the explanation here. Just open the file, and then take the exception.

  • dcastro Thank you for the reply. The file is already open.

  • @Fabríciosimonealanamendes You’re welcome! Did it work? If so, don’t forget to mark the answer as correct :)

  • No friend, he took another part of the text.

  • @Fabriciosimonealanamendes What part? The text you put in the question is an exact copy of the file you are using?

  • The document can several lines, one or several, precise texts that appear in the 3rd columns.

  • @You should clarify the question better then. In the question, you just said "I need to take only the value 132008281" - this is very different from "I need the texts that appear in the 3rd columns"

  • @Fabríciosimonealanamendes I edited the answer, now will get the values in the 3rd column. Try again

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.