日期:2014-05-18  浏览次数:20968 次

C# 连续写入TXT文件
我想问一个问题,我用zedgraph一边采集波形,一边存入txt文件:

但发现2个程序基本一样,但一个行,一个不行,不知道这是为什么?????

第一个程序,,为行,可以:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ZedGraph;
using System.IO;

namespace ZGControlTest
{
  public partial class Form1 : Form
  {
  StreamWriter sw;
  int i, a, l;
  string filepath;
  PointPairList list = new PointPairList();
  PointPairList list2 = new PointPairList();
  PointPairList list3 = new PointPairList();
  PointPairList list4 = new PointPairList();
  public Form1()
  {
  InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e)
  {
  System.Windows.Forms.Timer time1 = new System.Windows.Forms.Timer();
  time1.Tick += new EventHandler(timer1_Tick);
  time1.Interval = 50;
  time1.Start();
  i = 0;
  a = 0;
  l = 0;
  SaveFileDialog saveFileDialog = new SaveFileDialog();
  saveFileDialog.Filter = "文本文件(*.txt)|*.txt";
  if (saveFileDialog.ShowDialog() == DialogResult.OK)
  {
  filepath = saveFileDialog.FileName;
  sw = new StreamWriter(filepath);
  }
  }

  private void timer1_Tick(object sender, EventArgs e)
  {
  if (a == 1)
  {
y=0;y2=1;y3=2,y4=3;
  string w = y.ToString() + " " + y2.ToString() + " " + y3.ToString() + " " + y4.ToString()+"\r\n";
  sw.Write(w);
  list.Add(x, y);
  list2.Add(x, y2);
  list3.Add(x, y3);
  list4.Add(x, y4);
  zg1.AxisChange();
  zg1.Invalidate();
  }
  else
  {
  }
  }

  private void button1_Click_1(object sender, EventArgs e)
  {
  if (button1.Text == "开始采集")
  {
  a = 1;
  button1.Text = "停止采集";
  }
  else if (button1.Text == "停止采集")
  {
  sw.Close();
  a = 0;
  button1.Text = "开始采集";
  }
  }

开始采集时,波形一边存入txt,一边显示出来,没问题

但是上面的程序不是我想要的,我想要把上面的功能移植到另一个程序中去,移植后如下所示:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZedGraph;
using System.IO;

namespace 上位机软件构想
{
  public partial class Form7 : Form
  {
  StreamWriter sw;
  PointPairList list = new PointPairList();
  PointPairList list2 = new PointPairList();
  PointPairList list3 = new PointPairList();
  PointPairList list4 = new PointPairList();
  int i;
  string filepath, write;
  publ