✅ 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
Can you give an example of what the file contains?
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
maybe experiment with
File.ReadAllLines
hmmm ok thanks
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
/r/n?
the CR LF symbols
what's your doubt
i’m pretty new to c# so idk what /r/n means
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 linuxooo ok gotcha thank you!
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
ooo ok i see, ill try this out!