views:

30

answers:

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

namespace TimerApp4
{
    class Program
    {
        public static int k;
        static void Main(string[] args)
        {
            Timer t = new Timer(1000);
            t.Elapsed += new ElapsedEventHandler(SaniyelikIs);
            t.Start();
            k = 0;
            Console.Read();
        }

        static void SaniyelikIs(object o, ElapsedEventArgs a)
        {
            TextWriter tw = null;
            k++;
            if (k == 0)
            {
                tw = new StreamWriter("TextFile1.txt");

                // write a line of text to the file

                tw.WriteLine(DateTime.Now);
            }
            else
                tw.WriteLine(DateTime.Now);


            // close the stream
            tw.Close();

        }
    }
}

i can run it but "new StreamWriter("TextFile1.txt"); " gives me error: Unassigned local variable. That is results. How can i ru it

+3  A: 

You're only creating the StreamWriter in the true half of your if statement. Your code would look better if it was something like this:

    TextWriter tw = new StreamWriter("TextFile1.txt");
    k++;
    if (k == 0)
    {
        // write a line of text to the file
    }
    tw.WriteLine(DateTime.Now);

    // close the stream
    tw.Close();

However, I've also noticed that you initialise k to zero and only ever increment it, so if (k == 0) is only ever going to evaluate to false.

ChrisF
+1 for beating me to it, with a clearer explanation!
AdaTheDev
A: 

The problem is in the logic around your use of k:

k++;
if (k == 0)

You increment k before the if block, which means the "if (k == 0)" block that instantiates the StreamWriter is not hit. It instead goes to the else block which attempts to use tw, but it hasn't actually been instantiated (still null).

AdaTheDev