0

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.

  • 3
    You must close the file before trying to read it in again with `File.ReadLines()`. – 500 - Internal Server Error Dec 11 '22 at 17:49
  • What exactly are you stuck on? I haven't tried your code, but it looks like it should write the text out OK. If you now want to read the number of lines, just use the code in the question you linked. Having said that, if you keep a track of how many numbers you are writing, you won't even need to read the file back again. – Avrohom Yisroel Dec 11 '22 at 17:49

1 Answers1

2
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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142