Refresh test file like console app. But How?
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 whol开发者_运维知识库e 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();
}
}
}
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());
}
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.
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.
精彩评论