SharkRetriever
SharkRetriever

Reputation: 214

Writing console lines to file

I have a console app in c# and am trying to make it so that all the lines in the console are written into a file. I have tried using a streamwriter.

using (StreamWriter writer = new StreamWriter(@"location", true))
{
    writer.WriteLine(Console.ReadLine());
}

But using these methods the output text file was still empty. Am I missing something?

Solution: write this at the place where you want to start recording the text

        Console.Clear();
        StringWriter sw = null;
        sw = new StringWriter();
        Console.SetOut(sw);

write this at the end

    string s = sw.GetStringBuilder().ToString();
        File.WriteAllText(@"file location", s);

text wouldn't display on console if I do that but does not matter in this case.

Upvotes: 1

Views: 2277

Answers (2)

Adilson de Almeida Jr
Adilson de Almeida Jr

Reputation: 2755

I think you need learn, how to use Streams, for after, work with the console output stream. You can see how to do it here: http://msdn.microsoft.com/en-us/library/system.console.out.aspx

Upvotes: -1

Pencho Ilchev
Pencho Ilchev

Reputation: 3241

StringWriter sw = null;
        try
        {
            sw = new StringWriter();
            Console.SetOut(sw);
            Console.Write("test");
            string s = sw.GetStringBuilder().ToString();
            File.WriteAllText("c:\\BACKUP\\temp.txt", s);
        }finally
        {
            if(sw != null)
            {
                sw.Dispose();
            }
        }

Upvotes: 4

Related Questions