2015-05-20 4 views
0

Я пишу тестовые примеры в веб-драйвере Selenium, и я хочу выводить результаты в файл журнала. Тест-файлы должны быть пронумерованы в строке в текстовом файле. Нумерация была достигнута, но добавление тестовых примеров - это то, чего я не смог достичь. Проблема заключается в цикле for, где я хочу добавить комбинацию переменных, передаваемых по ссылке. Эти переменные будут тестовыми. Если требуется больше объяснений, сообщите мне.Append 'Вызывается ссылочными переменными' в текстовый файл

Проблема в том, что объединение определенных переменных только добавляет одно значение для всех.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.IO; 

namespace ConsoleApplication5 
{ 
    class Class1 
    { 
     public static int counter; 
     public static String[] test = {"1", "2" }; 
     public static String[] test1 = { "a", "b" }; 

     public static void Main(String[] args) 
     { 
      new Class1().testing2(); 
     } 

     public String testing(String ab, String cd) 
     { 
      //Count the number of times the method is called 
      ++counter; 
      //Write it to a text file 
      File.WriteAllText(@"C:\Users\ken4ward\Desktop\Tidy\WriteLines.txt", counter.ToString()); 
      //Read from that text file 
      String Readfiles = File.ReadAllText(@"C:\Users\ken4ward\Desktop\Tidy\WriteLines.txt"); 
      //Convert to integer 
      Int32 myInt = Int32.Parse(Readfiles); 
      //Store in array variable 
      String[] start = new String[myInt]; 
      //iterate through 
      for (int i = 0; i < myInt; ++i) 
      { 
       **start[i] = (i + 1).ToString() +ab +cd;** 
      } 
      //Write into another text file on new lines 
      File.WriteAllLines(@"C:\Users\ken4ward\Desktop\Tidy\Writing.txt", start); 

      String gb = ab; String th = cd; String you = ab + cd; 
      return you; 
     } 

     public void testing2() 
     { 
      foreach(var item in Class1.test) 
      { 
       foreach (var item1 in Class1.test1) 
       { 
        String test = testing(item, item1); 
        Console.WriteLine(test); 
        Console.ReadLine(); 
       } 
      } 
     } 
    } 
} 

Когда я запустил его, вывод в текстовом файле:

1 2b 
2 2b 
3 2b 
4 2b 

, что я хочу, чтобы вывести в текстовом файле:

1 1a 
2 1b 
3 2a 
4 2b 
+1

Ваш вопрос непонятен. Можете ли вы показать, что выводит метод и что вы действительно хотели его вывести? –

+0

Спасибо. Я отредактировал его, добавил результат, который я ожидаю. – kehinde

+0

Что означает эта строка? ** start [i] = (i + 1) .ToString() + ab + cd; ** '? Вы имеете в виду 'start [i] = (i + 1) .ToString() + ab + cd;'? – J3soon

ответ

1

Добавить глобальную переменную

public static String[] lines = { }; 

Изменение testing() к этому:

public String testing(String ab, String cd) 
    { 
     //Count the number of times the method is called 
     ++counter; 
     //Write it to a text file 
     File.WriteAllText(@"C:\Users\ken4ward\Desktop\Tidy\WriteLines.txt", counter.ToString()); 
     //Read from that text file 
     String Readfiles = File.ReadAllText(@"C:\Users\ken4ward\Desktop\Tidy\WriteLines.txt"); 
     //Convert to integer 
     Int32 myInt = Int32.Parse(Readfiles); 
     //Store in array variable 
     String start = myInt.ToString() + ab + cd; 
     //Store the new data in the array 
     Array.Resize(ref lines, lines.Length + 1); 
     lines[lines.GetUpperBound(0)] = start; 
     //Write into another text file on new lines 
     File.WriteAllLines(@"C:\Users\ken4ward\Desktop\Tidy\Writing.txt", lines); 
     //String gb = ab; String th = cd; 
     String you = ab + cd; 

     return you; 
    } 

С WriteAllText средства для перезаписи файла.

for (int i = 0; i < myInt; ++i) 
{ 
    start[i] = (i + 1).ToString() +ab +cd; 
} 

Код выше (ab + cd) равен 2b, что означает, что вы меняете номер строки, и 2b остается неизменным.

+0

Лучше всего добавить выходной файл. Но это будет немного сложнее. – J3soon

+0

Могу ли я создать переменную «линии»? Это вызывает ошибку, которая не существует в текущем контексте. Цените. Если да, какой тип данных? – kehinde

+0

Добавьте глобальную переменную 'lines'. См. Первую строку моего ответа. – J3soon

Смежные вопросы