2016-02-11 9 views
0

Мой код довольно длинный, но это та часть, в которой я застрял. У меня есть инструкция try в начале перед моими циклами. Но теперь я хочу взять свою информацию, которая находится в ListBox, и отправить ее в текстовый файл, который у меня уже есть в папке отладки. Я хотел бы просто извлечь мои результаты из списка и записать их в файл population.txt.Запись элементов из списка в текстовый файл в C# с аргументом try-catch

// переменный пользовательский ввод, хранение в UserInput попробовать { если (double.TryParse (startTextbox.Text, из начала)) { если (double.TryParse (averageTextbox.Text, из среднего)) { if (double.TryParse (daysTextbox.Text, out days)) { // process int count = 1; while (count < = дни) { // расчет двойной выход; output = start * Math.Pow ((1 + average/100), count - 1);

      //display the results in the listbox 
          populationListBox.Items.Add("The approximate population for " + 
           count + " day(s) is " + output.ToString("n2")); 

          //count the days 
          count = count + 1; 
         } 
         //used to text statement 
         //populationListBox.Items.Add("End of while loop"); 

         count = 1; 
         do 
         { 
          //calculation 
          double output; 
          output = start * Math.Pow((1 + average/100), count - 1); 

          //display the results in the listbox 
          populationListBox.Items.Add("The approximate population for " + 
           count + " day(s) is " + output.ToString("n2")); 

          //count the days 
          count = count + 1; 
         } while (count <= days); 
         //used to text statement 
         //populationListBox.Items.Add("End of do-while loop"); 

         //int count; 
         for (count = 1; count <= days;) 
         { 
          //calculation 
          double output; 
          output = start * Math.Pow((1 + average/100), count - 1); 

          //display the results in the listbox 
          populationListBox.Items.Add("The approximate population for " + 
           count + " day(s) is " + output.ToString("n2")); 

          //count the days 
          count = count + 1; 
         } 
         //used to text statement 
         //populationListBox.Items.Add("End of for loop"); 


        } 
        else 
        { 
         //error message for input 
         MessageBox.Show("Invalid input for number of days to multiply."); 
        } 
       } 
       else 
       { 
        //error message for input 
        MessageBox.Show("Invalid input for average daily increase."); 
       } 
      } 
      else 
      { 
       //error message for input 
       MessageBox.Show("Invalid input for starting days"); 
      } 


      StreamWriter outputFile; 
      outputFile = File.CreateText("population.txt"); 

      outputFile.WriteLine("Approximate population: "); 
      outputFile.WriteLine(populationListBox.Items); 
      outputFile.ToString(); 
      outputFile.Close(); 
     } 

     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
     } 
+0

вам нужно, чтобы показать нам содержимое ListBox, прежде чем мы можем сказать вам, как записать его в файл ... –

+0

Пробовали ли вы ' foreach (строка s в listBox1.Items) {outputFile.WriteLine (s); } '? –

ответ

1

Вы можете использовать библиотеку, такую ​​как FileHelper, для выполнения своей работы. Это с открытым исходным кодом и бесплатно. Если вы хотите использовать только FileIO от платформы .NET вы можете сделать это также

using (StreamWriter sr = File.CreateText("population.txt")) 
{ 
     foreach (string s in listBox.Items) 
     { 
      sr.WriteLine(s); 
     } 
}