little problem with lists in c#

Hello, im trying to create a txt file with all the catched data in the variable x. i have a boolean variable (SaveData) which will enable to start the saving of this data. but at the end in txt file i only can catch one value ( the last one before disable the boolean variable), any idea what i can do to catch all the data ?

the X variable is data from sensor

void Txt_Data()
    {
        StreamWriter File = new StreamWriter ("TestTest1.txt");
        SortedList<float,int> output = new SortedList<float,int> (){};
        if (SaveData == true) {

            j++;
            output.Add (x, j);
      

      
            foreach (KeyValuePair<float,int> listItem in output) {
                File.Write (listItem.ToString () + "\r\n");
                File.Close();

            }
        }


    }

You are closing your StreamWriter within foreach loop. After first iteration you should get ObjectDisposedException. Try calling File.Close() outside of foreach loop or even better use using:

using (StreamWriter writer = new StreamWriter("TestTest1.txt"))
{
    foreach (KeyValuePair<float, int> keyValuePair in sortedList)
    {
        writer.Write(keyValuePair + "\r\n");
    }
}
1 Like