Writing Output to a File
How do I write some Console.WriteLine()
values to a file loca开发者_StackOverflow中文版ted in C:\
?
app.exe > c:\somefile.txt
or
Console.SetOut(File.CreateText("c:\\somefile.txt"));
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:\.
Maybe this is what you want?
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;
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");
}
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");
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.
精彩评论