如何从上次输出重新启动进程并创建一个可以存储最后输出数据的文件?

时间:2012-02-28 04:49:01

标签: c# .net file

如何创建可存储输出信息的文件?例如,我需要得到一个输出,其中名称重复10000次..一旦我停止运行程序并重新开始,它应该显示新输出与旧的值...如果我停在它之间,说第4000次,它再次从4001再次开始,而不是一遍又一遍..我如何在这个程序中使用文件?有人可以帮我整个程序吗? 该计划是 -

namespace Time_Writer
{
    class Program
    {
        static int count = 1;
        static double seconds;
        private static System.Timers.Timer aTimer;

        static void Main(string[] args)
        {
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed +=new System.Timers.ElapsedEventHandler(aTimer_Elapsed);
            aTimer.Interval = 5000;
            aTimer.Enabled = true;
            Console.WriteLine("Press Enter To Exit The Program\n");
            Console.ReadLine();

        }
        private static void aTimer_Elapsed(object source, ElapsedEventArgs e)
        {
            Console.WriteLine("Name is Yap {0}", e.SignalTime);
            seconds += 5;
            count += 1;
            if (count>10)
            {
                aTimer.Enabled = false;
                Console.WriteLine("\n\nTimer is off at {0}\n\n", e.SignalTime.TimeOfDay.ToString());
            }
        }


    }
}

1 个答案:

答案 0 :(得分:1)

在这个例子中,我只是将count变量的位保存到同一目录中的文件中。

        static void Main(string[] args)
    {
        ReadCountFromFile();

        aTimer = new System.Timers.Timer();
        aTimer.Elapsed += new System.Timers.ElapsedEventHandler(aTimer_Elapsed);
        aTimer.Interval = 5000;
        aTimer.Enabled = true;
        Console.WriteLine("Press Enter To Exit The Program\n");
        Console.ReadLine();

        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_DomainUnload);
    }

    private static void ReadCountFromFile()
    {
        try
        {
            if (File.Exists(".\\mynumber.dat"))
            {
                using (var file = File.Open(".\\mynumber.dat", FileMode.Open))
                {
                    byte[] bytes = new byte[4];
                    file.Read(bytes, 0, 4);
                    count = BitConverter.ToInt32(bytes, 0);
                    Console.WriteLine("Count = {0}", count);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Problem reading file.");
        }
    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        using (var file = File.Open(".\\mynumber.dat", FileMode.OpenOrCreate))
        {
            var buffer = BitConverter.GetBytes(count);
            file.Write(buffer, 0, buffer.Length);
        }
    }