Count Number of Lines in text file c# and also write to the same file .

hello ,

I am trying to populate a field in my text file and it needs the number of records in the text file, meaning the lines.
each time I try to use the code below , I get an error saying that the file is being used as I am writting other records to it .
                 int count = 0;
                string line;
                TextReader reader1 = new StreamReader(@"\sqlfile.txt");
                while ((line = reader1.ReadLine()) != null)
Who is Participating?
KimputerConnect With a Mentor Commented:
Open, write, close.
Then open, read, close. Etc.

Did you make a typo by the way?  (Reader.close should be reader1.close? )
anarki_jimbelConnect With a Mentor Commented:
Just to add to the above post...

In pas I worked a lot with txt files (e.g., code files, etc.) and found it useful to load file content into a list (of strings). I.e., each line becomes a list item in a memory. In this case it's easy to address any line.
After manipulating  the content I dumped the text back to the file. Later I found this was quite common approach.
KimputerConnect With a Mentor Commented:
Also to add to the above post...
If indeed a LOT of operations are done (and the read/write file is big), it's true it will speed up:

near beginning of program
open, read to memory (array/list or some sorts), close. Etc.
Operate/Write/read array/list(s)
open, write from memory, close file.
near beginning of program
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.