-2

Is there any better/faster way to identify the length of line inside file in C#, by giving its line number I have a console application where I need to find length of each line present in the file where I will be giving the line number in the file

int lineno = 5
int linelen = File.ReadLines(@"C\Document\myfile.txt").skip(lineno).Take(1).First().Length
Praveen N
  • 120
  • 1
  • 7
  • 3
    Is this process slow currently? How slow is it? What speed would be acceptable? It's hard to do anything about performance without some benchmarks. – ADyson Jun 09 '22 at 12:40
  • 1
    You seem to have a fundamental misunderstanding of what a "line" in a file is. All files are a single stream of characters which can contain `\n` and/or `\r` characters. A "line" is just a human convenience. – gunr2171 Jun 09 '22 at 12:42
  • Not sure why you have so much LINQ in there, `File.ReadLines(@"C\Document\myfile.txt")[lineno].Length` is so much shorter (and requires way fewer allocations) – UnholySheep Jun 09 '22 at 12:45
  • 1
    @UnholySheep Need to use `.ElementAt(lineno)`, ReadLines gives an IEnumerable – gunr2171 Jun 09 '22 at 12:48
  • @gunr2171 Ah, right - I had it mixed up with `ReadAllLines`... – UnholySheep Jun 09 '22 at 12:49
  • I have 200 mb file where I have around 968355 lines. I have a function process on each of line in the file , this function will needs the length of each of line in the file and function passes line number to get length of the lines – Praveen N Jun 09 '22 at 12:53
  • 1
    `.Take(1)` is unnecessary here. – dr.null Jun 09 '22 at 13:26

1 Answers1

0

this is an example, since its not clear what you need ar result: code can be simplified base on what exectly you need in output. also, can add a where condition and take, skip, etc

var result = File.ReadAllLines("C:\\1\\test\\mishka.txt")
    .Select((str, index) => new {index = index, line = str, length = str.Length});
    Console.Write(result);

enter image description here

Power Mouse
  • 727
  • 6
  • 16
  • 2
    Using `File.ReadAllLines` is potentially going to lead to terrible performance, especially with large files. Use `File.ReadLines` instead. See here: https://stackoverflow.com/questions/21969851/what-is-the-difference-between-file-readlines-and-file-readalllines – DavidG Jun 09 '22 at 12:54
  • @DavidG, i agreed. it was an example to show how to appy linq ReadLines() is an iterator, it helps you to avoid calling ToArray() you need array to apply Select(). again this is an example – Power Mouse Jun 09 '22 at 19:42