how to find out the number of characters in the c # file

  • What kind of characters? But generally GetFileSize () - Vladimir Martyanov
  • all that is, for example, as string.length - whoami
  • @whoami as String.Length - just reading the entire file as one big line, and calling her String.Length - PashaPash

2 answers 2

In order not to load the entire file into memory, you can:

var charCount = 0; using (var reader = new StreamReader(@"path_to_file", detectEncodingFromByteOrderMarks: true)) { while (reader.Read() > -1) { charCount++; } } 
  • +1, but then it’s better to read the buffer in blocks, rather than character by character. - i-one
  • So StreamReader blocks into memory and reads, one of the constructor overloads allows you to set this buffer. The default is 4096 bytes. - Eugene
  • It seems to me that a cycle like char[] buff = new char[buffSize]; int cntRead = 0; while ((cntRead = reader.Read(buff, 0, buffSize)) > 0) charCount += cntRead; char[] buff = new char[buffSize]; int cntRead = 0; while ((cntRead = reader.Read(buff, 0, buffSize)) > 0) charCount += cntRead; faster slip. - i-one
  • one
    Perhaps not tested. In response, I showed a working example and quite simple to understand, but how to develop it further the programmer's work. - Eugene

We read the file (by default, the encoding is UTF-8 ):

 var txt = File.ReadAllText("myfile.txt"); 

After that look txt.Length .