根据列表检查文本文件的内容<string>
checking the contents of a text file against a List<string>
因此,我正在尝试检查文本文件的内容,以查看文本文件中是否存在列表 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;
}
}
因此,我正在尝试检查文本文件的内容,以查看文本文件中是否存在列表 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;
}
}