从网站下载字符串,检查每一行是否包含字符串

Download string from website, check each line if it contains string

我创建了一个包含纯文本的简单页面,如下所示:

Line 1
Line 2
Line 3
Line 4

然后我制作了一个包含文本框的 c# Winform 应用程序 文本框文本类似于

Line 1
Line 2

我想检查文本框行是否包含从我的网站下载的任何字符串

这是我试过但不起作用的方法

int pub = 0;
int priv  = 0;
WebClient data = new WebClient();
string reply = data.DownloadString("http://mytoosupd.000webhostapp.com/public-keys.html");

for (int i=0; i < textBox1.Lines.Length; i++)
{
  if (textBox1.Lines[i].Contains(reply + "\n"))
  {
    pub++;
    label5.Text = pub.ToString();
    continue;
  } 
  else if (!textBox1.Lines[i].Contains(reply))
  {
    priv++;
    label4.Text = priv.ToString();
  }
}

您可以在那里 break 而不是 continue。在你的情况下你不需要 else if 。只有 else 会起作用。如果您的目标只是检查,那么您可以使用 bool 变量而不是 int.

SplitIntersectAny就够简单了

string reply = data.DownloadString(..);

var result = reply
   .Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries)
   .Intersect(textBox1.Lines)
   .Any();

Debug.WriteLine($"Found = {result}");

更新

// to get a list of the intersected lines, call `ToList()` instead
var list = reply
   .Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries)
   .Intersect(textBox1.Lines)
   .ToList();


// list.Count() to get the count
// use this list where ever you like
// someTextBox.Text = String.Join(Environment.NewLine, list);
// or potentially
// someTextBox.Lines = list.ToArray();