C
C#7mo 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
SG977mo ago
Can you give an example of what the file contains?
Ewan
Ewan7mo 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
SG977mo ago
maybe experiment with File.ReadAllLines
Ewan
Ewan7mo ago
hmmm ok thanks
WEIRD FLEX
WEIRD FLEX7mo 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
Ewan7mo ago
/r/n?
WEIRD FLEX
WEIRD FLEX7mo ago
the CR LF symbols what's your doubt
Ewan
Ewan7mo ago
i’m pretty new to c# so idk what /r/n means
WEIRD FLEX
WEIRD FLEX7mo 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
Ewan7mo ago
ooo ok gotcha thank you!
WEIRD FLEX
WEIRD FLEX7mo 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
Ewan7mo ago
ooo ok i see, ill try this out!
Want results from more Discord servers?
Add your server
More Posts