1

Skip to TLDR version if you aren't up for an explanation of my logical processing.

I've been fiddling around with a program which does the following: On button click, reads random line from a locally stored text document, without the ability to repeat itself

however what I wan't it to do is to be able to read from a URL, not a locally stored solution.

So my following code is the current function and what I tried, and what it resulted with.

string[] readText = File.ReadAllLines(@"path\file.txt");
Random rnd = new Random();
textBox1.Text=(readText[rnd.Next(readText.Length)]);

Naturally all this does is read from a file stored in the path section, then creates a random generator and makes the textbox' output a random line from the entire document.

What I tried to do with the URL, and it partially worked..

WebClient webCon= new WebClient();
string webData = webCon.DownloadString("URL");
textBox1.Text = webData;

followed by the following to generate a random line of the document:

Random rnd = new Random();
textBox1.Text = ((webData[rnd.Next(webData.Length-1)]));

However this was invalid and I then had to convert char to string the following way, which resulted in a really funny and utterly useless textbox.

Random rnd = new Random();
textBox1.Text = char.ToString((webData[rnd.Next(webData.Length-1)]));

TL;DR version

I have a program that reads from a local file with the following method:

string[] readText = File.ReadAllLines(path)

and then generates a random line from said document to display in a textbox like so:

Random rndm = new Random();
            textBox1.Text=(readText[rndm.Next(readText.Length)]);

However what I want for it to be able to do, is read from a URL (online document). I tried completing this task with the webClient method but it resulted in needing to convert char to string on my textbox from a URL.

WebClient webCon= new WebClient();
string webData = webCon.DownloadString("URL");
textBox1.Text = webData;

I hope this question isn't close enough to a reposte as possible, I did ensure to check thoroughly first on relevant threads and couldn't really complete my task. Thank you in advance!

Storm
  • 25
  • 5
  • `rnd.Next(readText.Length)` needs to be `rnd.Next(readText.Length-1)` - `50` Entries means `0 - 49` - could lead to errors when `rnd = 50` – Felix D. Apr 06 '17 at 11:00
  • I guess u want to split the `webData` by [NewLine](http://stackoverflow.com/a/1547483/4610605)? – Felix D. Apr 06 '17 at 11:01
  • @FelixD. Of course! That was a typo on my behalf, I even had it in another similar line of code! Corrected. (the actual code had the -1) And to answer that split question: I don't know? I'm not sure. – Storm Apr 06 '17 at 11:02
  • 2
    When you split your webData you get the `string[]` again and then it's just the same as before to get a random line of it – Felix D. Apr 06 '17 at 11:03
  • Consider that the response from the WebClient _might_ not even contain any NewLines chars. It depends on how the HTML is formatted, thus the split might not work at all, or at random. Obviously, if the document you read is maintained by yourself the issue is nonexistent. – r41n Apr 06 '17 at 12:19
  • 1
    @r41n Thank you for that input, as that could potentially change things for people besides myself, as the URL I read is a static link with updatable 'raw' text inside it, so I didn't have to fiddle through all the HTML to get the proper text. That might be helpful for others, so thank you for bringing it up! – Storm Apr 07 '17 at 12:44

1 Answers1

0

How about using the string.Split() method? It would boil down to something like this:

//\n denotes the newline caracter
var lines = webData.Split('\n');

you can now proceed with the lines array just as you did with the result you've obtained from the file.

I'd also recommend you use the WebClient like this:

using (var webCon = new WebClient()) 
{
    string webData = webCon.DownloadString("URL");
    //process webData
}

the using {} part makes sure your WebClient is correctly disposed (which frees up resources).

Some more explanation to your thought process:
strings are arrays composed of chars, so if you access an element inside, I'll be of type char:

string myVal = "hi mom";
char myChar = myVal[0];

The Random object should only be constructed once in your application, so make sure that if you generate a lot of random numbers in a short time you reuse the same Random object (or you might receive multiple times the same values)

Full example:

private static Random _random = new Random();
static void Main(string[] args)
{
    using (var webCon = new WebClient())
    {
        var webData = webCon.DownloadString("http://stackoverflow.com/questions/43253136/");
        var lines = webData.Split('\n');
        var myRandomLine = lines[_random.Next(0, lines.Length - 1)];
        MyTextBlock.Text = myRandomLine;
    }
}
Florian Moser
  • 2,583
  • 1
  • 30
  • 40
  • greatly appreciate the help; I'll look into it and try to get it to work using this; and of course I only had one of the random generators running at a time, I had the one I didn't use commented out! – Storm Apr 06 '17 at 11:45
  • I'm sorry but I simply cannot put this together and get it to work. I can't see how this should be organized to make it functional. - I am simply that bad, or my mind is just not functioning at the time. – Storm Apr 06 '17 at 13:22
  • Leave it for today, and try again tomorrow, that helps sometime if you're stuck :) I'll try to do a complete example – Florian Moser Apr 06 '17 at 13:33
  • There doesn't seem to be any issues with the code you provided me with, nor the logic behind it, but how do I apply that (local variable) string being myRandomLine to a textbox? I can't get it to work, having tried very little - but having a tiny knowledge of what I'm even working with. Also: Why create a private static random rather than just calling it in a function? – Storm Apr 06 '17 at 17:40
  • You can assign `myRandomLine` to the `TextBox.Text` property, everything should work just fine. I've made a short example, download it at https://github.com/famoser/StackoverflowExamples/tree/master/43253136 (all relevant code is in `MainWindow.xaml`). I'm using `private static Random` so I can reuse the same object in other methods if I ever need to, but this is a personal choice, you can do it differently. – Florian Moser Apr 06 '17 at 21:08
  • that was more than enough to guide me towards the right direction! I thank you, and I will assign you as an appropriate answer now that I finally understand it and got it to work! Thank you. – Storm Apr 06 '17 at 21:27
  • I am cleaning house, and will remove the repository I linked to above. On the unlikely event that someone still needs this, I have pasted the relevant code & instructions to https://dotnetfiddle.net/Gujmkq – Florian Moser Aug 16 '20 at 11:36