views:

47

answers:

3

i need your help! if my codes runs, Console appears and write datetime.now line by line, but if i open my txt(TextFile1.txt) . i don't see console command results.

console result in black pad

  • 22:30 29.01.2010
  • 22:31 29.01.2010
  • 22:32 29.01.2010
  • 22:33 29.01.2010

BUT; on the other hand; if i open textfile (Textfile1.txt), i see only one time result , i want to see whole time result like above.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.IO;

namespace TimerApp4
{
    class Program
    {

        static void Main(string[] args)
        {
              Timer t = new Timer(1000);
                t.Elapsed += new ElapsedEventHandler(SaniyelikIs);
                t.Start();
                Console.Read();
                t.Stop();
        }

        static void SaniyelikIs(object o, ElapsedEventArgs a)
        {
            // write a line of text to the file
            StreamWriter tw = new StreamWriter("TextFile1.txt");
            tw.WriteLine(DateTime.Now);
            Console.WriteLine(DateTime.Now + "\n");
            // close the stream
            tw.Close();

        }
    }
}
A: 

I'm not sure I understand your question or problem. However, in your code you close the stream in the SaniyelikIs method. Since this method will get called every second, the second time you call it the stream will have already been closed and WriteLine will throw an exception.

statichippo
i rearrange my question. Please look above!
Phsika
+1  A: 

Don't close the StreamWriter until the program exits. Also, since you need to access the TextWriter from the Timer event, you need to use a public or private variable.

private static TextWriter tw { get; set; }

static void Main(string[] args)
{
    using (tw = new StreamWriter("TextFile1.txt"))
    {
        Timer t = new Timer(1000);
        t.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        t.Start();
        Console.Read();
        t.Stop();
        tw.Close();
    }

static void OnTimedEvent(object sender, ElapsedEventArgs args)
{
    // write a line of text to the file
    tw.WriteLine(DateTime.Now.ToString());
}
Ryan
your codes give me error that is the same as my codes' error:Error 3 An object reference is required for the non-static field, method
Phsika
The code is now updated and works.
Ryan
A: 

If I am not mistaken, you want to be able to see the file in realtime and output the latest changes to the console for that file yes? If so, then maybe you should look into using the FileSystemWatcher class to do this for you?

Hope this helps, Best regards, Tom.

tommieb75