c#如何通过proccess从列表框写入文本文件

时间:2015-03-03 08:41:17

标签: c# file text export

我试图在文本文件中添加x和y数据,就像所有x结果一行一行,y结果在x旁边,例如; 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();                        
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

//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);
  }          
}

答案 1 :(得分:0)

不要嵌套你的循环,但是在下一个循环之后将它们放在一起:

    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);
    }