Hari Gillala
Hari Gillala

Reputation: 11926

Writing Output to a File

How do I write some Console.WriteLine() values to a file located in C:\?

Upvotes: 2

Views: 277

Answers (7)

Mark H
Mark H

Reputation: 13907

Sounds like you just want to log some data. Rather than calling Console.WriteLine() directly, you should just use some kind of delegate to output to both the file and console.

Action<string> log = Console.WriteLine;
log += str => File.AppendText("c:\\file.log", str + Environment.Newline);

log("LOG ME");

Upvotes: 2

Rozuur
Rozuur

Reputation: 4165

use StreamWriter for writing with using, which ensures the correct usage of IDisposable objects.

    using (StreamWriter writer = new StreamWriter("C:\filename"))
    {
        writer.Write("some text");
        writer.WriteLine("some other text");
    }

Upvotes: 2

Betamoo
Betamoo

Reputation: 15960

        StreamWriter sw = new StreamWriter(@"C:\1.txt");
        sw.WriteLine("Hi");
        sw.WriteLine("Hello World");
        sw.Close();

and do not forget to use System.IO

       using System.IO;

Upvotes: 2

leppie
leppie

Reputation: 117330

  • app.exe > c:\somefile.txt

or

  • Console.SetOut(File.CreateText("c:\\somefile.txt"));

Upvotes: 10

dzendras
dzendras

Reputation: 4751

Maybe this is what you want?

Upvotes: 2

Rockcoder
Rockcoder

Reputation: 8479

Take a look at a System.IO.File class. It has a lot of useful methods for file manipulation, like File.WriteAllLines(fileName) for example.

Upvotes: 1

dandan78
dandan78

Reputation: 13925

Use the StreamWriter class:

var outputfile = new StreamWriter("c:\\outputfile.txt");
outputfile.Writeline("some text"); 
outputfile.Close();

However, depending on your version of Windows, you might not have permission to write to C:\.

Upvotes: 3

Related Questions