1

I'm quite a noob at programming and I've been stuck at this for a while now. I'm using the following code to get continuous data output streamed to a command prompt. How can I ensure that the output gets copied to a text file after closing the prompt manually?

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"]);
        }
    }
}
Anton Sizikov
  • 9,105
  • 1
  • 28
  • 39
Vigo
  • 11
  • 2
  • You could easily call your programm from commandline and pipe the result to a file: `stuff.exe > output.txt` – ckruczek Jun 24 '15 at 12:43
  • closing the prompt manually exits your application so I suggest you create your app as a process to achieve that! – Bellash Jun 24 '15 at 12:44
  • change your console writes to use a custom class `MyConsoleWriter`, and write to the file and console with each call. Then you can be sure the file is always up to date. Or, even better, put that behind and interface. – Jonesopolis Jun 24 '15 at 12:45
  • Maybe the content of this question can be useful: http://stackoverflow.com/questions/420429/mirroring-console-output-to-a-file – sblandin Jun 24 '15 at 12:52

3 Answers3

3

It will be much better to log every console output to a file as it happens. Instead of waiting to write to file when the app is closed manually. To save yourself a lot of coding, you can use log4net to handle the logging.

Oladipo Olasemo
  • 2,010
  • 24
  • 31
0

There's several different ways of approaching this, and with a bit of research I'm sure you could find a few, however this is the solution I would use for this particular action :

As Jonesy mentioned in the comments, I would firstly tidy up your Main. Create a separate class to perform the console writeline and the text output at the same time.

In this class perhaps use a loop to output the data to a file as and when it happens, therefore you wouldn't have to code in the logic when the console is closed manually, which in turn would cover unexpected errors and loss of logs.

0

This might work.

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");
}
Binoj Antony
  • 15,886
  • 25
  • 88
  • 96