Ritwik
Ritwik

Reputation: 611

how to count number of characters in a file in C#?

I tried

    string str1 = File.ReadAllText("D:\\this.txt");
    str1.Length;
    byte[] fileBytes = File.ReadAllBytes("D:\\this.txt");
    fileBytes.Length;

gone thru similar question but each time same problem arises, it counts carriage return and new line also like in my file data is

123
456
7 

it is showing '11' but output should be '7' help needed EDIT: i want to count every element which have ASCII greater than or equal to 32

Upvotes: 1

Views: 5384

Answers (2)

weston
weston

Reputation: 54781

You could load all lines, then add all the lengths of each line together using linq:

var numberOfCharacters = File.ReadAllLines(@"D:\this.txt").Sum(s => s.Length);

Alternative

Doesn't count whitespace except space or controls chars. Requirements are fuzzy, but should put you on right track.

 var numberOfCharacters = File.ReadAllText(@"D:\this.txt").
    Count(c => c==" " ||
    (!Char.IsControl(c) &&
     !Char.IsWhiteSpace(c)));

Upvotes: 7

Will Custode
Will Custode

Reputation: 4594

Well character count will always (and should always) count non-visible characters because they are still characters. You can look on the MSDN for what qualifies as a whitespace character and use Replace.

I would like to make note that, although the other responses will work, they're neglecting the fact that carriage return and line-feed are not the only non-visible whitespace characters you will encounter. And different OS's will handle "Enter" or "Return" differently. Some with just \n and others with '\r\n'.

Upvotes: 1

Related Questions