5

I would just like to apologise for mposting this, there are a lot of questions like this here but I can't find one that is specific to this.

I have a list and each item contains a DateTime, int and a string. I have successfully written all list items to a .txt file which is delimited by commas. For example 09/04/2015 22:12:00,10,Posting on Stackoverflow.

I need to loop through the file line by line, each line starting at index 0, through to index 2. At the moment I am able to call index 03, which returns the DateTime of the second list item in the text file. The file is written line by line, but I am struggling to read it back with the delimiters and line breaks.

I am sorry if I am not making much sense, I will appreciate any help, thank you.

Jack
  • 53
  • 1
  • 1
  • 6
  • Use StreamReader, read line by line, keep an incrementing integer which will point you to the current line and split the string and use the elements. – Hozikimaru Apr 09 '15 at 21:22
  • @SurgeonofDeath I have implemented the code that i486 commented as a method of solving my problem, but I think I will change to StreamReader later, thank you for your time. – Jack Apr 09 '15 at 21:42
  • Please be aware that the naive solution of reading a line at a time, and splitting on commas, [does not work](http://secretgeek.net/csv_trouble) for comma-separated text files. CSV files can contain commas and newlines in data, can contain comments, be localized, and do many other things you aren't handling. For anything but the most trivial text you need a [CSV parser](http://stackoverflow.com/questions/9642055/). – Dour High Arch Apr 09 '15 at 21:58

3 Answers3

14
string[] lines = File.ReadAllLines( filename );
foreach ( string line in lines )
{
  string[] col = line.Split(',');
  // process col[0], col[1], col[2]
}
i486
  • 6,491
  • 4
  • 24
  • 41
4

You can read all the lines at once via var lines = File.ReadAllLines(pathToFile);. Then you can split each line into an array of fields via:

foreach (var line in lines) {
    String[] fields = line.Split(',');
}

If you don't have any stray commas in your file and the only commas are true delimiters, this will mean that fields will always be a 3 element array, with each of your fields in succession.

DWright
  • 9,258
  • 4
  • 36
  • 53
  • 1
    BTW, If the file is large, @Surgeonofdeath approach using Streams will be better. – DWright Apr 09 '15 at 21:30
  • Hi DWright, thank you for your help, I think I will use Streams but at the moment my problem is solved, thanks again! – Jack Apr 09 '15 at 21:40
1

Alternatively, you can do the following:

    public static List<Values> GetValues(string path)
    {
        List<Values> valuesCollection = new List<Values>();;

        using (var f = new StreamReader(path))
        {
            string line = string.Empty;
            while ((line = f.ReadLine()) != null)
            {
                var parts = line.Split(',');
                valuesCollection.Add(new Values(Convert.ToDateTime(parts[0]), Convert.ToInt32(parts[1]), parts[2]); 
            }
        }

        return valuesCollection;
    }

    class Values
    {
        public DateTime Date { get; set; }

        public int IntValue { get; set; }

        public string StringValue { get; set; }

        public Values()
        {
        }

        public Values(DateTime date, int intValue, string stringValue)
        {
            this.Date = date;
            this.IntValue = intValue;
            this.StringValue = stringValue;
        }
    }

You could then iterate through the list or collection of values and access each object and its properties. For example:

Console.WriteLine(values.Date);
Console.WriteLine(values.IntValue);
Console.WriteLine(values.StringValue);
James Shaw
  • 839
  • 1
  • 6
  • 16