简体   繁体   English

我如何打开多个URL以在C#中读取

[英]How can I open multiple urls to read in c#

Here's what I got so far: 这是到目前为止我得到的:

string[] urls = new string[2];
urls[1] = "https://exampletext.com/example1";
urls[2] = "https://exampletext.com/example2";

Console.WriteLine("\nSearching url...\n");
int count=1;
while (count < 3)
{
    var url = urls[count];
    var client = new WebClient();
    using (var stream = client.OpenRead(url))
        using (var reader = new StreamReader(stream))
        {
            string linetext;

            while ((linetext = reader.ReadLine()) != null)
            {
                 Console.WriteLine(linetext);
            }

        }
    count++;
}

How do I make it so that I cycle to those two(or potentially more) urls? 我该如何做才能循环到这两个(或可能更多)URL? I was thinking doing using (string[] urls = new string[2]){...} but I'm not sure if that'd work. 我当时正在考虑using (string[] urls = new string[2]){...}但不确定是否可以使用。 I'm very new to VS and c#, so please excuse my ignorance. 我是VS和c#的新手,请原谅我的无知。

Your array goes from 0 to 1, but you're looping from 1 to 2. (I'm surprised you're even able to set urls[2] to a value without an exception.) 您的数组从0到1,但是从1到2循环。(令您惊讶的是,您甚至可以毫无例外地将urls[2]设置为一个值。)

Semantically it would probably make more sense if you just use a foreach loop: 从语义上讲,如果仅使用foreach循环,则可能更有意义:

foreach (var url in urls)
{
    // your logic
}

Use parallel foreach which will access all multiple urls 使用并行的foreach将访问所有多个URL

https://msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx https://msdn.microsoft.com/zh-CN/library/dd460720(v=vs.110).aspx

  • Use a for loop, or a foreach loop. 使用for循环或foreach循环。
  • All Indexes start at 0. 所有索引均从0开始。

code: 码:

string[] urls = new string[2];
urls[0] = "https://exampletext.com/example1";
urls[1] = "https://exampletext.com/example2";

Console.WriteLine("\nSearching url...\n");
for(int count = 0; count < urls.Length; count++)
{
    var url = urls[count];
    var client = new WebClient();
    using (var stream = client.OpenRead(url))
        using (var reader = new StreamReader(stream))
        {
            string linetext;

            while ((linetext = reader.ReadLine()) != null)
            {
                 Console.WriteLine(linetext);
            }

        }
}

Array in c# start with 0 index, you are initializing it with 1 you missed zero. c#中的数组以0索引开头,您使用1错过了零来对其进行初始化。

alternatively you can try something like: 或者,您可以尝试以下操作:

foreach(string url in new String[] {"https://exampletext.com/example1", "https://exampletext.com/example2", "https://exampletext.com/example3"}) 
{
   // read url here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM