Martin
Martin

Reputation: 77

Reading from txt file to array/list<>

I need to read all of .txt file and save data to array/list. File looks like this:

row11    row12    row13
row21    row22    row23
row31    row32    row33

between strings are only spaces.

Next I will insert data from array/list<> to mysql, but it is not problem. Thanks.

EDIT: I need insert 3 columns to mysql like .txt file.

Upvotes: 0

Views: 2998

Answers (4)

James Ko
James Ko

Reputation: 34629

Here's a nifty one-liner based off Amadeusz's answer:

var lines = File.ReadAllLines(fileName).Select(l => l.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries)).SelectMany(words => words);

Upvotes: 0

mausworks
mausworks

Reputation: 1625

As long as there are never spaces in the "values", then a simple line-by line parser will work.

A simple example

var reader = new StreamReader(filePath);

var resultList = new List<List<string>>();

string line;

while ((line = reader.ReadLine()) != null)
{
    var currentValues = new List<string>();

    // You can also use a StringBuilder
    string currentValue = String.Empty;

    foreach (char c in line)
    {
        if (Char.IsWhiteSpace(c))
        {
            if (currentValue.Length > 0)
            {
                currentValues.Add(currentValue);

                currentValue = String.Empty;
            }
            continue;
        }

        currentValue += c;
    }

    resultList.Add(currentValues);
}

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

You can use File.ReadLines() to read the lines from the file, and then Regex.Split() to split each line into multiple strings:

static IEnumerable<String> SplitLines(string path, string splitPattern)
{
    foreach (string line in File.ReadAllLines(path))
        foreach (string part in Regex.Split(line, splitPattern))
            yield return part;
}

To split by white space, you can use the regex pattern \s+:

var individualStrings = SplitLines(@"C:\path\to\file.txt", @"\s+");

You can use the ToList() extension method to convert it to a list:

List<string> individualStrings = SplitLines(@"D:\test\rows.txt", @"\s+").ToList();

Upvotes: 0

Amadeusz Wieczorek
Amadeusz Wieczorek

Reputation: 3207

Use String.Split(Char[], StringSplitOptions) where the first parameter specifies that you want to split your string using spaces and tabs, and the second parameter specifies that you ignore empty entries (for cases where there are multiple spaces between entries)

Use this code:

var lines = System.IO.File.ReadAllLines(@"D:\test.txt");
var data = new List<List<string>>();
foreach (var line in lines)
{
    var split = line.Split(new[]{' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);
    data.Add(split.ToList());
}

Upvotes: 3

Related Questions