因此,我尝试检查文本文件的内容,以查看文本文件中是否存在列表 textwords
中包含的任何值。
但是,当执行代码时,它始终认为消息不包含 textwords
列表中包含的任何字符串。
使用的代码如下。
任何有关此问题的帮助将不胜感激。
List<string> textwords = new List<string>();
using (var UnacceptableWords = new StreamReader("fileLocation"))
{
while (!UnacceptableWords.EndOfStream)
{
string[] row = UnacceptableWords.ReadLine().Split(',');
string Column1 = row[0];
textwords.Add(Column1);
}
}
directory = new DirectoryInfo("filelocation");
files = directory.GetFiles("*.txt");
foreach (FileInfo file in files)
{
using(StreamReader Message = new StreamReader(file.FullName))
{
string MessageContents = Message.ReadToEnd();
if(MessageContents.Contains(textwords.ToString()))
{
MessageBox.Show("found a word");
}
MessageBox.Show("message clean");
}
}
最佳答案
string.Cointains()
方法接受一个字符串,但您将已转换为字符串的 List
传递给它。
List.ToString() != 列表中包含的字符串值
为此,您必须迭代数组并一次传递其中的每个元素
foreach(string keyword in textwords)
{
if(MessageContents.Contains(keyword))
{
MessageBox.Show("found a word");
break;
}
}
关于c# - 根据 List<string> 检查文本文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36472677/