How to get Number Of Lines without Reading File To End
Is there a way to get Number of Lines within a Large Text file ,but without Reading the File content or reading file to end and Counting++.
Maybe there are some File Attributes ,but cannot find it out at all . Because i might be in some cases where i should get Total Number of Line's and compare it to Current line to display the Percentage,and just for a Percentage Display it开发者_Go百科 might be stupid to read first all Content than read it Again to Display the raw text at user.
bests
No. You have to read the file. Consider storing it at the beginning of the file or in a separate file when you write the file if you want to find it quickly without counting.
Note that you can stream the file, and it's surprisingly fast:
int count = File.ReadLines(path).Count();
Because i might be in some cases where i should get Total Number of Line's and compare it to Current line to display the Percentage,and just for a Percentage Display it might be stupid to read first all Content than read it Again to Display the raw text at user.
Oh, just get the file size and the length of each line in bytes and keep a cumulative count of the number of bytes processed so far.
No, there is no other way.
A file is not line based (or even character based), so there is no meta information about the number of lines (or even number of characters). The only meta data about the content is the length in bytes.
If you have some additional information about the file, for example that each line is exactly the same length, and it uses an 8-bit encoding so that the number of characters is the same as the number of bytes, you could calculate the number of lines from the file size.
As Guffa and Jason said, there is no way to get the lines other than reading to the end.
To solve your problem differently:
If you are interested only in the percentage display you COULD try to acummulate that value from the total file size and the line you are currently at. You need to apply some voodoo tricks there to get the actual bytes read (like say, you have read to line 10, and a total of 200 bytes or whatever) and the file size is 400bytes. You could probably guess that you are at 50%, without giving needing to know a total line number.
Thats just some random numbers there, btw.
精彩评论