I have a working solution although different to my question as it doesn't involve an array at all. See my other question here Adding rows to second column ONLY - populating data using a for loop and the actual question is the answer for this one. I have used just FileInfo and DataGridView.
How do you count the amount of lines from a file that is read through a byte array directly? NOT from the file itself
-
31-08-2022 - |
Question
I have used OpenFileDialog where the user opens a file and data will be displayed in the DataGridView Table. I have created and read the file through a byte array, and now I want to get the total line count from THIS - NOT from the actual file using File.ReadAllLines.
Creating the byte array that reads the file:
byte[] array = File.ReadAllBytes(path);
Reading line count from a file:
// This is a no-no!
int lineCount = File.ReadAllLines(path).Count();
Solution 3
OTHER TIPS
Not entirely sure what you're asking. You are opening a binary or ascii file? Are you trying to count the lines in the datagridview after you bind it? Try
int count = DataGridView.RowCount;
You can use the Count function on the array :
array.Count(n => (char)n == '\n') + 1;
This code doesn't deal with empty lines. The + 1 is for the last line.
As the first method doesn't work, I suggest you to use the following :
var str = System.Text.Encoding.Default.GetString(array);
var lineCount = str.Split(new[] { Environment.NewLine }, int.MaxValue, StringSplitOptions.None).Count();
It's not optimized as it performs a full copy.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow