与主题声明一样,我需要在每次执行程序计时器时保存一个值。
这是代码和我的程序。
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值。 但每次我运行代码时,所有值都会丢失。因此将值保存到文件中。当计时器下次运行时,它会从文件中获取值并将新值添加到旧值,经过一段时间后我得到正确的计数器值。
答案 0 :(得分:3)
您可以在项目的设置中声明一个整数值:
而不是在你的代码中使用它:
private void btn1_Click(object sender, RoutedEventArgs e)
{
Settings.Default.Counter = 123;
Settings.Default.Save();
}
答案 1 :(得分: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;
}
}
答案 2 :(得分:0)
“但每次我运行代码时,所有值都会丢失。”
如果您希望保留原始值,则需要附加现有文件:
using (StreamWriter writer = new StreamWriter("counter.txt", true)) {
writer.Write(t);
writer.Close();
}