0

I'm currently faced some problem which is cannot convert/transfer the console output the a specific text file. I'm also tried use the below code. The problem is, it only can write first line from the console and the following line is cannot write to the text file and also the console is exit. Anyone help me please.

Regards, Thanes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace consoletotext
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstname;
            string myoutline;
            Console.Write(""); // whatever type here
            firstname = Convert.ToString(Console.ReadLine());
            string path = @"file.txt";
            myoutline = firstname;

            if (!File.Exists(path))
            {
                using (StreamWriter sw = File.CreateText(path))
                {
                    sw.WriteLine(myoutline);

                }
            }
            Console.ReadKey();

        }


    }
}
cg thanes
  • 9
  • 1
  • 5
  • 1
    possible duplicate of [How to save Console.WriteLine output to text file?](http://stackoverflow.com/questions/4470700/how-to-save-console-writeline-output-to-text-file) – Thomas Aug 07 '15 at 08:32

1 Answers1

2

If I understand correctly, you want to continually write input to a file. You need a while loop where you check some value condition, like "exit", for example. I also think you want to append to a file, not create a new one for each line read, so that is what I have demonstrated:

    static void Main(string[] args)
    {
        string input;
        Console.Write(""); // whatever type here
        input = Console.ReadLine();
        string path = @"file.txt";

        using (StreamWriter sw = new StreamWriter(path, true))
        {
            while (input != "exit")
            {
                sw.Write(input);
                input = Console.ReadLine();
            }
        }
    }
Crowcoder
  • 11,250
  • 3
  • 36
  • 45