-1

I have a csv file in my file explorer windows 10. This file contains a list of rows e.g.:

John, 5656, Phil, Simon,,Jude, Helen, Andy
Conor, 5656, Phil, Simon,,Jude, Helen, Andy

I am an automated tester using C#, selenium and visual studio. In the application I am testing, there is an upload button which imports the csv file.

How do I randomly change the second number automatically so the update would be 1234 on the first row, 4444 on the second row(just append randomly). I think I would need a random generator for this.

Any advice or snippets of code would be appreciated.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Hyper
  • 9
  • 3

3 Answers3

0

Do you want to append the CSV file before its uploaded to the program or after? Either way it would look something like this:

public File updateFile(string filePath){
    List<string> modifiedNames;
    using (StreamReader sr = File.OpenText(path))
    {
        string s;
        while ((s = sr.ReadLine()) != null)
        {
            s = s + randomlyGeneratedSuffix();
            newEntries.add(s)

        }
    }

    using (StreamWriter sw = new StreamWriter("names.txt")) {

        foreach (string s in modifiedNames) {
            sw.WriteLine(s);
        }

    }
    // return new file?
}
GeersJ
  • 105
  • 2
  • 8
0

Reading the file before uploading, changing the numbers on the second position in csv and writing it again to disk should work. Here is a very simple approach, to help you get started:

        var fileLines = File.ReadAllLines("file.csv");
        var randomGenerator = new Random();
        var newFileLines = new List<string>();
        foreach (var fileLine in fileLines)
        {
            var lineValues = fileLine.Split(',');
            lineValues[1] = randomGenerator.Next(1000, int.MaxValue).ToString();
            var newLine = string.Join(",", lineValues);
            newFileLines.Add(newLine);
        }

        File.WriteAllLines("file.csv", newFileLines);
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
-1

Instead of updating an existing CSV file for testing I would generate a new one from code.

There are a lot of code examples online how to create a CSV file in C#, for example: Writing data into CSV file in C#

For random numbers you can use the random class: https://learn.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.7.2

Niels van Reijmersdal
  • 2,038
  • 1
  • 20
  • 36
  • But the upload button looks in the file explorer – Hyper Mar 06 '19 at 13:20
  • You generate the file, save it somewhere Selenium can access it, upload it with the button. Maybe you need a shared drive between the test-runner and the Selenium agent. Or upload it somewhere on a webserver so Selenium can download it. – Niels van Reijmersdal Mar 06 '19 at 13:24