Break a txt file into multiple items in a string list

Asked

Viewed 1,171 times

1

I have a txt file with 2000 names. When I load into a list, Count is 1 and not 2000. Of course, because as it comes to a text file is only 1. It turns out, that the file is organized with \n\r inside it. Even though I give a Split(), I still can’t load a list with 2000 records or items. How do I do this? That is, take a txt file and divide it into a string list with multiple items, using as separator the \n\r?

I used this code to fill the array that comes from the txt file:

string[] text = new[] { System.IO.File.ReadAllText(path) };

I did it this way. I thought it was ugly, but I couldn’t find a more beautiful solution, I had to do two foreach and it makes me kind of boring.

string[] text = new[] { System.IO.File.ReadAllText(path) };

            foreach (var item in text)
            {
                string[] linha = item.Split('\n');
                foreach (var i in linha)
                {
                    lista.Add(i);
                }

            }
  • I didn’t know how to fill the array linha in a single time. I did the foreach, because it will always pass only once, but it’s kind of scary that. The right thing would be to load the array linha in one go, but I don’t know how to do it.

3 answers

3

Could do so:

using System.Collections.Generic;
using System.IO;
using System.Linq;
List<string> texto = File.ReadAllLines(path).ToList();

0

You can scroll through the entire txt with its giant string and feed the list to each found unit.

If the separator is n r, scroll through your String looking for this separator and use Substring to pass each of the items to the list.

0

TextReader _Reader = new StreamReader(@"C:\ArquivoTexto.txt");

string[] _Splitado = _Reader.ReadToEnd().Split('|');

List<string> _Lista = new List<string>(_Splitado);

Does this solve? Just change the file name and the character you want to use as a separator.

Browser other questions tagged

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