Home > Blockchain >  Read Random Pastebin Lines
Read Random Pastebin Lines

Time:09-26

I'm trying to find a way to read a random line from a Pastebin

       string line = "";
            WebClient WC = new WebClient();
            List<string> TEST = new List<string>();

            Random Rand = new Random();

            line = WC.DownloadString("Pastebin");
            TEST.Add(line);

            button1.Text = TEST[Rand.Next(1, TEST.Count)];

But the problem with the code is that it responds to this It gives this error System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'

Is there a possible Solution

And if you can, Can you explain how you fixed it so I can solve it in the future.

CodePudding user response:

So.. you download a single string from pastebin

You put this one string in a new list, so it ended up at index 0. The list contains 1 string, so list count is 1

You asked Random for a new random value between 1 and 1, which will make it give you 1

And you then asked the list to supply you the string at index 1.. but there isn't any string at that index. The only valid list index is 0. This results in an out of range exception.

I suggest you split your downloaded text and AddRange it to the list

TEXT.AddRange(line.Split('\n'))

Also, get random to return you a value between 0 and count otherwise you'll never get that first line

  • Related