1

I want to prevent CMD from closing automatically after running the program.

Code:

static void Main(string[] args)
    {

        FileStream textfsw = new FileStream("fileone.txt", FileMode.Append, FileAccess.Write); // CREATING FILE
        StreamWriter textsw = new StreamWriter(textfsw);

        Console.Write(" Enter your ID: ");
        int ID = int.Parse(Console.ReadLine());
        Console.Write(" Enter your Name: ");
        string Name = Console.ReadLine();
        Console.WriteLine(" Thank you! your logged in as" +Name+ +ID);

        textsw.Close();
        textfsw.Close();

        FileStream textfs = new FileStream("fileone.txt", FileMode.Open, FileAccess.Read); // READING A FILE USING ReadAllLines
        StreamReader textsr = new StreamReader(textfs);

        String[] lines = File.ReadAllLines("fileone.txt");
    }

Screenshot: after running screenshot

I want to show the following after running and prevent cmd from closing:

Thank you! your logged in as John Smith 12345

Any answers would be appreciated.

Thank you.

Mina Hafzalla
  • 2,681
  • 9
  • 30
  • 44

2 Answers2

7

You can use Console.ReadKey(), which waits until a single key is pressed (and returns it, but we don't need that in this case).

This is an alternative to Console.ReadLine() and Console.Read() which need the user to press enter.


As an asside, when using file access (and working with objects that implement IDisposable generally) you should use using statements to ensure all resources are freed up in all cases:

using(FileStream textfs = new FileStream("fileone.txt", FileMode.Open, FileAccess.Read))
{
    using(StreamReader textsr = new StreamReader(textfs))
    {
        // Do things with textfs and textsr
    }
}

Also note that since you're using File.ReadAllLines you don't need any of the above as it does it for you.

George Duckett
  • 31,770
  • 9
  • 95
  • 162
  • 1
    @MISHAK You should accept his answer by clicking the green tick below the vote count if it is sufficient. I just want to add that using `Process.GetCurrentProcess().WaitForExit()` is another good method of stopping the Console from closing in certain situations. – User 12345678 Apr 25 '13 at 13:33
4

Use Console.Read() at the end to achieve this.

Console.WriteLine("Thank you! your logged in as" + Name + ID);
Console.Read();

As George mentions, you can also use ReadKey() or you can use ReadLine();

Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304