C
C#12mo ago
Ewan

✅ How do i count how many lines there are in a file

So i want my program to output values from a text file (notepad) but i want it to be different depending on the number of lines a text files uses. So if it has only 1 line of writing i want it to print something, if it has 2 lines... etc But how do i count how many lines there are in a file and store that in a variable?
12 Replies
SG97
SG9712mo ago
Can you give an example of what the file contains?
Ewan
EwanOP12mo ago
it doesnt matter what it contains does it? i just wanna count how many lines a file has and store the number in a variable idk the file can contain: hello goodbye thats 2 lines so id like 2 to be stored in a variable but idk how to count the number of lines
SG97
SG9712mo ago
maybe experiment with File.ReadAllLines
Ewan
EwanOP12mo ago
hmmm ok thanks
Omnissiah
Omnissiah12mo ago
without using unnecessary memory you can just read the file and count how many \r\n you find although be careful, some files use only one of those
Ewan
EwanOP12mo ago
/r/n?
Omnissiah
Omnissiah12mo ago
the CR LF symbols what's your doubt
Ewan
EwanOP12mo ago
i’m pretty new to c# so idk what /r/n means
Omnissiah
Omnissiah12mo ago
a new line in a text file is made by these two characters on windows while on linux it's only LF this \ is called escaping, for when you need stuff like symbols so a string with a new line would be string stringWithNewLine = "blablabla\r\n"; on windows string stringWithNewLine = "blablabla\n"; on linux
Ewan
EwanOP12mo ago
ooo ok gotcha thank you!
Omnissiah
Omnissiah12mo ago
so they are all chars char a = 'a'; char lf = '\n'; you can also find for example what is the current new line for your system in a predefined constant
var myNewline = System.Environment.NewLine;
var myNewline = System.Environment.NewLine;
Ewan
EwanOP12mo ago
ooo ok i see, ill try this out!
Want results from more Discord servers?
Add your server