这是我到目前为止所得到的:
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++;
}
我如何制作它以便循环到那两个(或可能更多)的网址?我在考虑做using (string[] urls = new string[2]){...}
,但我不确定这是否有效。我对VS和c#都很陌生,所以请原谅我的无知。
答案 0 :(得分:2)
你的数组从0变为1,但是你从1循环到2.(我很惊讶你甚至能够将urls[2]
设置为没有异常的值。)
从语义上讲,如果你只使用foreach
循环可能会更有意义:
foreach (var url in urls)
{
// your logic
}
答案 1 :(得分:0)
使用将访问所有多个网址的并行foreach
https://msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx
答案 2 :(得分:0)
代码:
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);
}
}
}
答案 3 :(得分:0)
c#中的数组以0索引开头,你用1错过零来初始化它。
或者你也可以试试:
foreach(string url in new String[] {"https://exampletext.com/example1", "https://exampletext.com/example2", "https://exampletext.com/example3"})
{
// read url here
}