c# 如何根据进程从列表框中写入文本文件

c# how to write to a text file from list box as a result of proccess

我正在尝试在文本文件中添加 x 和 y 数据,例如逐行添加所有 x 结果和 x 旁边的 y 结果; 40,281516651,1,17956575 。但是在这段代码中,由于foreach,结果被多次覆盖。

        double z, d, x, k, y;
        d = double.Parse(textBox1.Text);

        for (double i = 0; i <= 90; i++)
        {
            k = Math.PI / 180;
            z = Math.Tan((i / 2 + 45) * k);
            x = (d / 3.141) * (Math.Sin(Math.PI * i / 180) - Math.Log(z));
            y = d / 3.141 * (Math.Cos((Math.PI * i) / 180) + (3.141 / 2));  
            listBox2.Items.Add(x);
            listBox1.Items.Add(y);
            listBox3.Items.Add(z);
            const string sPath = @"C:\Users\NET\Desktop\deneme.txt";
            StreamWriter SaveFile = new StreamWriter(sPath);   
            foreach (var item in listBox1.Items)
            {
                SaveFile.WriteLine(item);
                foreach (var a in listBox2.Items)
                {
                    SaveFile.WriteLine(a);
                }                     
            }                             
            SaveFile.Close();                        
            }
        }
    }
}
//fill the listBoxes
for (double i = 0; i <= 90; i++)
{
   k = Math.PI / 180;
   z = Math.Tan((i / 2 + 45) * k);

   x = (d / 3.141) * (Math.Sin(Math.PI * i / 180) - Math.Log(z));
   y = d / 3.141 * (Math.Cos((Math.PI * i) / 180) + (3.141 / 2)); 

   listBox2.Items.Add(x);
   listBox1.Items.Add(y);
   listBox3.Items.Add(z);
}

// write the text file
const string sPath = @"C:\Users\NET\Desktop\deneme.txt";
using(StreamWriter SaveFile = new StreamWriter(sPath))
{   
  for (int i=0; i<listBox1.Items.Count; i++)
  {
    string line = String.Format("{0},{1}", listBox1.Items[i], listBox2.Items[i]);
    SaveFile.WriteLine(line);
  }          
}

不要嵌套你的循环,而是一个接一个地放置它们:

    for (int i = 0; i <= 90; i++)
    {
        ...
        listBox2.Items.Add(x);
        listBox1.Items.Add(y);
        listBox3.Items.Add(z);
    }
    ...
    foreach (var item in listBox1.Items)
    {
        SaveFile.WriteLine(item);
    }
    foreach (var a in listBox2.Items)
    {
        SaveFile.WriteLine(a);
    }