如何将控制台输出保存到文件?

时间:2018-12-10 12:03:29

标签: c# file output

我想知道是否有人可以帮助我,我试图将控制台输出保存到文件中,但是它只接受一个输出,并且我希望它每次在控制台中显示时都接受并追加输出(每秒或多或少) ),我尝试了一些不同的方法,但似乎没有任何效果,我甚至不确定是否可行。

1)这是我的第一次尝试:它只需要一个控制台输出,但是据我了解,它应该重定向它。

                FileStream ostrm;
                StreamWriter writer;
                TextWriter oldOut = Console.Out;
                try
                {
                    ostrm = new FileStream("C:/Users/Joanne/Desktop/WriteLines3.txt", FileMode.OpenOrCreate, FileAccess.Write);
                    writer = new StreamWriter(ostrm);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Cannot open Redirect.txt for writing");
                    Console.WriteLine(e.Message);
                    return;
                }
                while(onvifPTZ != null) { 
                Console.SetOut(writer);
                Console.WriteLine("\t Act Value [" + curPan.ToString() +
                                                       "," + curTilt.ToString() +
                                                       "," + curZoom.ToString() + "]");
                Console.WriteLine("\t Ref Value [" + newPTZRef.pan.ToString() +
                                                       "," + newPTZRef.tilt.ToString() +
                                                       "," + newPTZRef.zoom.ToString() + "]");
                Console.WriteLine("\t Dif Value [" + dPan.ToString() +
                                                   "," + dTilt.ToString() +
                                                   "," + dZoom.ToString() + "]");
                Console.SetOut(oldOut);
                writer.Close();
                ostrm.Close();
                Console.WriteLine("Done");

2)那两个都没有重定向控制台

/*while (onvifPTZ != null)
                {


                    string[] lines = {"\t Act Value [" + curPan.ToString() +
                                                       "," + curTilt.ToString() +
                                                       "," + curZoom.ToString() + "]","\t Ref Value [" + newPTZRef.pan.ToString() +
                                                       "," + newPTZRef.tilt.ToString() +
                                                       "," + newPTZRef.zoom.ToString() + "]", "\t Dif Value [" + dPan.ToString() +
                                                   "," + dTilt.ToString() +
                                                   "," + dZoom.ToString() + "]" + Environment.NewLine };

                        string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                    using (StreamWriter outputFile = new StreamWriter(Path.Combine(mydocpath, "WriteLines1.txt")))
                    {
                        foreach (string line in lines)
                            outputFile.WriteLine(line);
                        outputFile.Flush();
                    }

3)

/* string path = @"c://Users//Joanne//Desktop//WriteLines.txt";

                   if (!File.Exists(path))
                   {
                       // Create a file to write to.
                      using (StreamWriter sw = File.CreateText(path))
                       {
                           while(onvifPTZ!=null){ 
                           sw.WriteLine("\t Act Value [" + curPan.ToString() +
                                                          "," + curTilt.ToString() +
                                                          "," + curZoom.ToString() + "]");
                           sw.WriteLine("\t Ref Value [" + newPTZRef.pan.ToString() +
                                                          "," + newPTZRef.tilt.ToString() +
                                                          "," + newPTZRef.zoom.ToString() + "]");
                           sw.WriteLine("\t Dif Value [" + dPan.ToString() +
                                                      "," + dTilt.ToString() +
                                                      "," + dZoom.ToString() + "]");
                               sw.Flush();
                               //sw.Close();
                           }
                       }
                   }


                  /*using (StreamWriter sw = File.AppendText(path)) {
                           while (onvifPTZ != null)
                           {


                               sw.WriteLine("\t Act Value [" + curPan.ToString() +
                                                              "," + curTilt.ToString() +
                                                              "," + curZoom.ToString() + "]");
                               sw.WriteLine("\t Ref Value [" + newPTZRef.pan.ToString() +
                                                              "," + newPTZRef.tilt.ToString() +
                                                              "," + newPTZRef.zoom.ToString() + "]");
                               sw.WriteLine("\t Dif Value [" + dPan.ToString() +
                                                          "," + dTilt.ToString() +
                                                          "," + dZoom.ToString() + "]");
                           sw.Flush();
                           //sw.Close();
                           }


                       }
                   using (StreamReader sr = File.OpenText(path))
                   {
                       string s = "";
                       while ((s = sr.ReadLine()) != null)
                       {
                           Console.WriteLine(s);
                       }
                   }




                  // Open the file to read from.
                  /* using (StreamReader sr = File.OpenText(path))
                   {
                       string s;
                       while ((s = sr.ReadLine()) != null)
                       {
                           Console.WriteLine(s);
                       }
                   }*/

似乎没有任何正常工作... 我的控制台看起来像这样,相机每移动一次,它都会附加一个值:

[1003]
myTimedFunction got called at 1003
     Act Value [2.777576E-05,0,0]
     Ref Value [0.06279052,0.0125581,0.06279052]
     Dif Value [0.06276274,0.0125581,0.06279052]
[2006]
myTimedFunction got called at 2006
     Act Value [2.777576E-05,0,0.020052]
     Ref Value [0.1253332,0.02506665,0.1253332]
     Dif Value [0.1253055,0.02506665,0.1052812]
[3006]
myTimedFunction got called at 3006
     Act Value [0.06586289,0.02461553,0.06845684]
     Ref Value [0.1873813,0.03747626,0.1873813]
     Dif Value [0.1215184,0.01286074,0.1189245]
[4007]
myTimedFunction got called at 4007
     Act Value [0.09025252,0.02461553,0.1652665]
     Ref Value [0.2486899,0.04973798,0.2486899]
     Dif Value [0.1584374,0.02512245,0.08342336]
[5008]
myTimedFunction got called at 5008
     Act Value [0.1146421,0.02461553,0.2651765]
     Ref Value [0.309017,0.0618034,0.309017]
     Dif Value [0.1943749,0.03718787,0.0438405]
[6008]
myTimedFunction got called at 6008
     Act Value [0.1300313,0.02461553,0.3089309]
     Ref Value [0.3681245,0.07362491,0.3681245]
     Dif Value [0.2380932,0.04900938,0.05919364]
[7009]
myTimedFunction got called at 7009
     Act Value [0.1453651,0.02461553,0.3681368]
     Ref Value [0.4257793,0.08515586,0.4257793]
     Dif Value [0.2804142,0.06054033,0.05764246]
[8009]
myTimedFunction got called at 8009
     Act Value [0.1606989,0.02461553,0.4256926]
     Ref Value [0.4817537,0.09635074,0.4817537]
     Dif Value [0.3210548,0.07173521,0.05606112]
[9010]
myTimedFunction got called at 9010
     Act Value [0.1850885,0.02461553,0.4815482]
     Ref Value [0.5358268,0.1071654,0.5358268]
     Dif Value [0.3507383,0.08254983,0.05427864]
[10010]
myTimedFunction got called at 10010
     Act Value [0.1935887,0.02461553,0.5225022]
     Ref Value [0.5877852,0.117557,0.5877852]
     Dif Value [0.3941965,0.09294152,0.065283]
[11010]
myTimedFunction got called at 11010
     Act Value [0.2179784,0.02461553,0.5454546]
     Ref Value [0.637424,0.1274848,0.637424]
     Dif Value [0.4194456,0.1028693,0.09196943]

但是实际上,我创建的文件只带有第一个值,仅此而已...

2 个答案:

答案 0 :(得分:0)

第一次尝试的方法是正确的,但是Console.SetOut是错误的。检查下面编写的代码段:

using (var ostrm = new FileStream("C:/Users/dervis.kayimbasioglu/Desktop/WriteLines3.txt", FileMode.OpenOrCreate, FileAccess.Write))
using (var writer = new StreamWriter(ostrm))
{
    Console.SetOut(writer);
    Console.WriteLine("test to be written in file");
    writer.Close();
    ostrm.Close();
}

Console.WriteLine("Done");

答案 1 :(得分:0)

肮脏的解决方案
将控制台输出存储在一个数组中,然后在关闭应用程序时使用

存储
File.WriteAllLines("path", array);

推荐的解决方案
使用许多日志记录库之一,例如log4net。我在某些项目中独自使用了它,我真的可以推荐它。它还具有一个NuGet软件包,您可以通过右键单击项目通过菜单“管理nuget软件包” 下载。

下面是一个如何使用log4net记录器的小示例

var log=LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

log.Info("Hello World");

此外,您还需要创建一个名称为 log4net.config 的配置文件。在这里,当我从log4net开始时,您有一个使用from this site的配置示例

<log4net>
<root>
  <level value="ALL" />
  <appender-ref ref="console" />
  <appender-ref ref="file" />
</root>
<appender name="console" type="log4net.Appender.ConsoleAppender">
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %level %logger - %message%newline" />
  </layout>
</appender>
<appender name="file" type="log4net.Appender.RollingFileAppender">
  <file value="myapp.log" />
  <appendToFile value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="5" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
  </layout>
</appender>
</log4net>

最后,您需要将此行添加到以下行的 AssemblyInfo.cs 中,以便程序加载配置文件

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]

我希望我的遮阳篷能帮上忙