I am trying to get the second value from a CSV file with 100 rows. I am getting the first 42 values then it stops… no error messege, or error handling at all for that matter. I am perplexed and am on a timeline. It is also doing it for a TSV file, but giving the first 43 results. Please help and let me know if it looks strange to you.
I am using streamreader, reading each line into a string array, splitting the array and taking the second value and adding it to a list…
string path = @"C:\Users\dave\Desktop\codes\testfile.txt";
StreamReader sr = new StreamReader(path);
List<string> stkno = new List<string>();
foreach (var line in path)
{
string s = sr.ReadLine();
string[] words = s.Split(',');
stkno.Add(words[1]);
}
var message = string.Join(",", stkno.ToArray());
MessageBox.Show(message);
Your
pathvariable is a string. That means when youforeachover it, you’re getting a sequence of characters – ‘C’ then ‘:’ then ‘\’ etc. I don’t think that’s what you mean to do…Here’s a simpler approach using
File.ReadLines:Or:
If you’re using .NET 3.5 and you don’t mind reading the whole file in one go, you can use
File.ReadAllLinesinstead.