0

就像主题声称我需要在每次程序计时器执行时保存一个值。

这是代码和我的程序。

using (StreamReader r = new StreamReader("counter.txt"))
{
    String line;


    while ((line = r.ReadLine()) != null)
    {
        Double coilVerdi = Convert.ToInt32(line);
        Int32 breddePlate = Convert.ToInt32(PlateBredde.Text);


        Double plateVekt = (breddePlate * 0.0016);
        Double svar = plateVekt += coilVerdi;
        coil.Text = svar.ToString();
        coil.Refresh();
    }


    r.Close();
}

Double t = Convert.ToDouble(coil.Text);
using (StreamWriter writer = new StreamWriter("counter.txt"))
{
    writer.Write(t);
    writer.Close();

}

当向程序添加新值时,将执行此代码。它的作用是计算一个 int 值。但是每次我运行代码时,所有值都会丢失。因此,我将值保存到文件中。当计时器下次运行时,它会从文件中获取值并将新值添加到旧值中,一段时间后我得到正确的计数器值。

4

3 回答 3

3

您可以在项目的设置中声明一个整数值:

在此处输入图像描述

而不是在你的代码中使用它:

private void btn1_Click(object sender, RoutedEventArgs e)
    {
        Settings.Default.Counter = 123;
        Settings.Default.Save();
    }
于 2012-05-08T11:08:33.253 回答
0

您可以将值存储为二进制数据,这样您就不必将其转换为文本并返回。

using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.IO;



 class Program
 {
   static void Main(string[] args)
   {
    AddCounter(5);
    Console.WriteLine(GetCounter());
    AddCounter(3);
    Console.WriteLine(GetCounter());
    AddCounter(7);
    Console.WriteLine(GetCounter());
  }


static void AddCounter(int nCounter)
{
    SetCounter(GetCounter() + nCounter);
}


static void SetCounter(int nValue)
{
    using (FileStream fs = new FileStream("counter.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            bw.Write(nValue);
        }
    }
}

static int GetCounter()
{
    int nRes = 0;
    using (FileStream fs = new FileStream("counter.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
        using (BinaryReader br = new BinaryReader(fs))
        {
            if (br.PeekChar() != -1)
            {
                nRes = br.ReadInt32();
            }
        }
    }
    return nRes;
}
 }
于 2012-05-08T10:58:49.900 回答
0

“但每次我运行代码时,所有值都会丢失。”

如果您希望保留原始值,则需要附加现有文件:

  using (StreamWriter writer = new StreamWriter("counter.txt", true)) {
    writer.Write(t);
    writer.Close();
  }
于 2012-05-08T15:09:51.600 回答