[英]Writing Output to a File
如何将一些Console.WriteLine()
值写入位于C:\\
的文件中?
app.exe > c:\\somefile.txt
要么
Console.SetOut(File.CreateText("c:\\\\somefile.txt"));
使用StreamWriter
类:
var outputfile = new StreamWriter("c:\\outputfile.txt");
outputfile.Writeline("some text");
outputfile.Close();
但是,根据您的Windows版本,您可能没有权限写入C:\\。
也许这就是你想要的?
使用StreamWriter
用于书写using
,从而确保正确使用IDisposable
对象。
using (StreamWriter writer = new StreamWriter("C:\filename"))
{
writer.Write("some text");
writer.WriteLine("some other text");
}
StreamWriter sw = new StreamWriter(@"C:\1.txt");
sw.WriteLine("Hi");
sw.WriteLine("Hello World");
sw.Close();
并且不要忘记使用System.IO
using System.IO;
听起来你只想记录一些数据。 您不应直接调用Console.WriteLine()
,而应使用某种委托输出到文件和控制台。
Action<string> log = Console.WriteLine;
log += str => File.AppendText("c:\\file.log", str + Environment.Newline);
log("LOG ME");
看一下System.IO.File类。 它有许多有用的文件操作方法,例如File.WriteAllLines(fileName)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.