is it possible to read csv file based on line. Like give a line number and it retrieves that particular line in CSV.
Thanks
is it possible to read csv file based on line. Like give a line number and it retrieves that particular line in CSV.
Thanks
If you just want to read a line of a text file(like csv), the easiest approach is using File.ReadLines and Enumerable.ElementAtOrDefault:
public static String getFileLine(String path, int indexOfLine)
{
return File.ReadLines(path).ElementAtOrDefault(indexOfLine);
}
Use it in this way:
String line = getFileLine(@"C:\Temp\CsvFile.csv", 99);
That returns the 100th line (or null if there are less than 100 lines).
Here's another similar method that returns a range of lines:
public static IEnumerable<String> getFileLines(String path, IEnumerable<int> lineIndices)
{
return File.ReadLines(path).Where((l, i) => lineIndices.Contains(i));
}
return the first 10 lines:
IEnumerable<int> range = Enumerable.Range(0,10);
IEnumerable<String> lines = getFileLines(@"C:\Temp\CsvFile.csv", range);
foreach (String line in lines)
Console.WriteLine(line);
Note that File.ReadLines is similar to a StreamReader, it does not read the whole file at once into memory(as FileReadAllLines), just as much as necessary.
Skip and Take, for example: var lines = File.ReadLines(path).Skip(19).Take(6); ( 20-25 -> 6 lines ). It'll not even raise an exception if the file has less than 25 lines, it will just return what is there or Enumerable.Empty<string> if there are less than 20 lines.ToList at the end to create a List<string>, otherwise you'll get problems with File.ReadLines which disposes the underlying stream on the first use (as opposed to File.ReadAllLines which returns an array).It depends on your goal here but you should probably do something like
while((line = readFile.ReadLine()) != null)
{
//Record line
}
Then once you've read the files data into memory you can consider querying by line.
You really should have considered googling this by the way, even Bing'ing it would have got you an answer.
Not sure what your motivation is - if it's performance, consider using some DB... a CSV is not a DB, it is just a big file... to read a specific line number you will need to read all preceding lines (though you don't need to parse them completely)... OR read the whole file into memory File.ReadAllLines - this gives you a string[] which you can access at any line you want... OR use File.ReadLines which gives you IEnumerable<string> which might be more memory-efficient/performant with big files...