【问题标题】:How do I save continuous console output to a text file in c#?如何将连续控制台输出保存到 c# 中的文本文件?
【发布时间】:2015-09-10 16:08:12
【问题描述】:

我在编程方面是个菜鸟,我已经被困了一段时间了。我正在使用以下代码将连续数据输出流式传输到命令提示符。手动关闭提示后,如何确保将输出复制到文本文件中?

public static void Main(string[] args)
{
    Connector connector;
    Console.WriteLine("HelloEEG!");

    // Initialize a new Connector and add event handlers
    connector = new Connector();
    connector.DeviceConnected += new EventHandler(OnDeviceConnected);
    connector.DeviceConnectFail += new EventHandler(OnDeviceFail);
    connector.DeviceValidating += new EventHandler(OnDeviceValidating);

    // Scan for devices across COM ports
    // The COM port named will be the first COM port that is checked.
    connector.ConnectScan("COM40");

    // Blink detection needs to be manually turned on
    connector.setBlinkDetectionEnabled(true);

    Thread.Sleep(400000);

    System.Console.WriteLine("Goodbye.");
    connector.Close();
    Environment.Exit(0);
}

// Called when a device is connected 
static void OnDeviceConnected(object sender, EventArgs e)
{
    Connector.DeviceEventArgs de = (Connector.DeviceEventArgs)e;

    Console.WriteLine("Device found on: " + de.Device.PortName);

    de.Device.DataReceived += new EventHandler(OnDataReceived);
}

// Called when scanning fails

static void OnDeviceFail(object sender, EventArgs e)
{
    Console.WriteLine("No devices found! :(");
}

// Called when each port is being validated
static void OnDeviceValidating(object sender, EventArgs e)
{
    Console.WriteLine("Validating: ");
}

// Called when data is received from a device
static void OnDataReceived(object sender, EventArgs e)
{
    Device.DataEventArgs de = (Device.DataEventArgs)e;
    DataRow[] tempDataRowArray = de.DataRowArray;

    TGParser tgParser = new TGParser();
    tgParser.Read(de.DataRowArray);

    /* Loops through the newly parsed data of the connected headset*/
    // The comments below indicate and can be used to print out the different data outputs. 
    for (int i = 0; i < tgParser.ParsedData.Length; i++)
    {
        //string temp = tgParser.ParsedData[1].ToString;
        //Console.WriteLine(tgParser.ParsedData.Length + " + " + temp);

        if (tgParser.ParsedData[i].ContainsKey("Raw"))
        {
            //Console.WriteLine("Raw Value:" + tgParser.ParsedData[i]["Raw"]);
            //Console.WriteLine("Raw Value:" + tgParser.ParsedData[i]["Raw"]);
        }

        if (tgParser.ParsedData[i].ContainsKey("PoorSignal"))
        {
            //The following line prints the Time associated with the parsed data
            //Console.WriteLine("Time:" + tgParser.ParsedData[i]["Time"]);
            Console.WriteLine("Time:" + tgParser.ParsedData[i]["Time"]);

            //A Poor Signal value of 0 indicates that your headset is fitting properly
            Console.WriteLine("Poor Signal:" + tgParser.ParsedData[i]["PoorSignal"]);

            poorSig = (byte)tgParser.ParsedData[i]["PoorSignal"];
        }

        if (tgParser.ParsedData[i].ContainsKey("Attention"))
        {
            //Console.WriteLine("Att Value:" + tgParser.ParsedData[i]["Attention"]);
            Console.WriteLine("Att Value:" + tgParser.ParsedData[i]["Attention"]);
        }

        if (tgParser.ParsedData[i].ContainsKey("Meditation"))
        {
            //Console.WriteLine("Med Value:" + tgParser.ParsedData[i]["Meditation"]);
            Console.WriteLine("Med Value:" + tgParser.ParsedData[i]["Meditation"]);
        }

        if (tgParser.ParsedData[i].ContainsKey("EegPowerDelta"))
        {
            //Console.WriteLine("Delta: " + tgParser.ParsedData[i]["EegPowerDelta"]);
            Console.WriteLine("Delta: " + tgParser.ParsedData[i]["EegPowerDelta"]);
        }

        if (tgParser.ParsedData[i].ContainsKey("BlinkStrength"))
        {
            //Console.WriteLine("Eyeblink " + tgParser.ParsedData[i]["BlinkStrength"]);
            Console.WriteLine("Eyeblink " + tgParser.ParsedData[i]["BlinkStrength"]);
        }
    }
}

【问题讨论】:

  • 您可以轻松地从命令行调用程序并将结果通过管道传输到文件:stuff.exe &gt; output.txt
  • 手动关闭提示会退出您的应用程序,因此我建议您将应用程序创建为实现此目的的过程!
  • 更改您的控制台写入以使用自定义类MyConsoleWriter,并在每次调用时写入文件和控制台。然后,您可以确保该文件始终是最新的。或者,更好的是,把它放在后面和界面。
  • 也许这个问题的内容会有用:stackoverflow.com/questions/420429/…

标签: c#


【解决方案1】:

最好将每个控制台输出记录到文件中。而不是在手动关闭应用程序时等待写入文件。为了节省大量编码,您可以使用 log4net 来处理日志记录。

【讨论】:

    【解决方案2】:

    有几种不同的方法可以解决这个问题,通过一些研究,我相信你可以找到一些,但是这是我将用于此特定操作的解决方案:

    正如 Jonesy 在 cmets 中提到的,我会首先整理您的 Main。创建一个单独的类来同时执行控制台写行和文本输出。

    在此类中,可能会使用循环将数据在发生时输出到文件中,因此您不必在手动关闭控制台时编写逻辑代码,这反过来会涵盖意外错误和丢失日志。

    【讨论】:

      【解决方案3】:

      这可能有效。

      public static void WriteToFileAndConsole()
      {
          string outFile = "ConsoleOut.txt";
          using (FileStream fileStream = new FileStream(outFile, FileMode.OpenOrCreate))
          {
              using (StreamWriter writer = new StreamWriter(fileStream))
              {
                  using (TextWriter originalConsoleOut = Console.Out)
                  {
                      Console.SetOut(writer);
                      Console.WriteLine("Hello To File");
                      Console.SetOut(originalConsoleOut);
                  }
              }
          }
          Console.WriteLine("Hello to console only");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-15
        • 2011-10-29
        相关资源
        最近更新 更多