将输出写入文件

时间:2011-01-14 11:58:20

标签: c#

如何将一些Console.WriteLine()值写入C:\中的文件?

7 个答案:

答案 0 :(得分:10)

  • app.exe > c:\somefile.txt

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

答案 1 :(得分:3)

使用StreamWriter类:

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

但是,根据您的Windows版本,您可能没有权限写入C:\。

答案 2 :(得分:2)

也许this是你想要的?

答案 3 :(得分:2)

使用StreamWriterusing一起撰写,以确保正确使用IDisposable个对象。

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

答案 4 :(得分:2)

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

并且不要忘记使用System.IO

       using System.IO;

答案 5 :(得分:2)

听起来你只想记录一些数据。您不应直接调用Console.WriteLine(),而应使用某种委托输出到文件和控制台。

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

log("LOG ME");

答案 6 :(得分:1)

看看System.IO.File类。它有很多有用的文件操作方法,例如File.WriteAllLines(fileName)。