Uuno Purhaturo
Uuno Purhaturo

Reputation: 21

Having problems with counting the numbers of lines within a textfile. C#

I'm making a program that lets you input numbers in a textfile until you input a blank space. It's then supposed to count the number of lines the user wrote and displey them. I'm having problems with the counting of the lines.

internal class Program
    {
        private static void WriteNumbers(string filename)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename);
                Console.WriteLine("Write numbers, [Enter] ends the loop");
                string input = Console.ReadLine();
                sw.WriteLine(input);

                while (input != "")
                {
                    Console.WriteLine("Write a new number:");
                    input = Console.ReadLine();
                    sw.WriteLine(input);
                }
                if (input == "")
                {
                    var lineCount = File.ReadLines(@"C:\Users\1234\source\repos\tsat0500\L10T2\bin\Debug\numbers.txt").Count();
                    Console.WriteLine($"Thank you, you added {lineCount} numbers into the file!");
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Something went wrong, terminating the user in 10 seconds." + ex.Message);
            }

        }

        static void Main(string[] args)
        {
            WriteNumbers("numbers.txt");
        }

I've tried writing the filename differently, but this is the only way the intelligence allows it to be used. I wrote it based on comments on this post:

Determine the number of lines within a text file

I have no idea how to make it work at this point.

Upvotes: 0

Views: 70

Answers (1)

nvoigt
nvoigt

Reputation: 77304

var lineCount = ...
Console.WriteLine($"Thank you, you added {lineCount} numbers into the file!");
sw.Close();

You are trying to read your file, while it is still open for writing. You need to close it first, then read it:

sw.Close();

var lineCount = ...
Console.WriteLine($"Thank you, you added {lineCount} numbers into the file!");

That said... you could simply use a counter in your loop, then you know how many lines you wrote, without reading the file again.

Upvotes: 2

Related Questions