How can I get the length in characters (not bytes) of a stream / file? Let’s assume the encoding for the file / stream is known (at runtime).
I’d rather not load the whole stream in memory, so I’m against using TextReader.ReadToEnd()
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Unless the encoding is a fixed-width one (the same number of bytes for every character – e.g. ASCII but not UTF-8), you’ll need to read the whole file – but it doesn’t need to be in memory. For example:
Used like this:
Note that this will count UTF-16 code units, which isn’t quite the same as Unicode characters or displayable glyphs, but in most cases it will be good enough. (Consider cases such as combining characters and surrogate pairs.)