Click here to Skip to main content
15,910,234 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I am new to c# programming.. I need help on how to store the data from my text file then store it in array.

My text file looks like this:

29/5/2015 9:10:07 AM 29
29/5/2015 9:10:07 AM 29
29/5/2015 9:10:08 AM 30

I only need to store 29,29,30 and so on
please help.. thanks!
Posted
Updated 28-May-15 15:35pm
v2

Check the sample program below. It reads your file line by line, then splits it into individual words (split on space) and then takes the last word and adds it into a list. You can convert this list into an int Array if you want.

C#
class Program
{
    static void Main(string[] args)
    {
        List<int> listOfNumbers = new List<int>();
        using (StreamReader sr = new StreamReader(@"C:\Test.txt"))
        {
            while (!sr.EndOfStream)
            {
                string line = sr.ReadLine();
                if (!string.IsNullOrEmpty(line))
                {
                    listOfNumbers.Add(Convert.ToInt32(line.Split(' ').Last()));
                }
            }
        }
    }
}
 
Share this answer
 
v2
C#
//You can do this  in two  lines  of code
//if you just want the substring after the last space

 string[] lines = File.ReadAllLines(@"C:\Test.txt");

   List<string> OutputLines = (from line in lines
                let index = line.LastIndexOf(' ')
                where index > -1 && index < line.Length - 2
                select line.Substring(index + 1)).ToList();

//Or, in fluent syntax

   List<string> OutputLines  =
                lines.Select((line) => new { text=line, index = line.LastIndexOf(' ') })
                    .Where(x => x.index > -1 && x.index < x.text.Length - 2)
                    .Select(x => x.text.Substring(x.index + 1))
                    .ToList();

//or, with a foreach loop

 List<string> OutputLines = new List<string>();
foreach (var line in lines)
            {
                int index = line.LastIndexOf(' ');
                if (index > -1 && index < line.Length - 2) 
                OutputLines.Add(line.Substring(index + 1));
                
            }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900