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.
Please use System.IO.StreamReader
and System.IO.StreamWriter
will work for reading and and writing to a csv file. They have ReadLine()
and WriteLine()
methods.
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.
If your file is not very big you can do this:
string line10 = File.ReadAllLines(@"<filename>", Encoding.Default).ElementAt(10);
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...