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();

        }


    }
}
1

1 Answer 1

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();
            }
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank You. This code is really helpful. But how could i write line by line to the text file that like most write in console form?
@cgthanes add a new line character: sw.Write(input + Environment.NewLine);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.