假设有一个包含文本的文本文件(例如:任何网站的内容)。 现在,如果我想从文本文件中匹配字符串 strA (即段落),即文本文件中的文本,则说a.txt包含字符串 strA ?
如何比较?
答案 0 :(得分:1)
我会做类似的事情:
bool containsString = File.ReadAllText(@"C:\test.txt").Contains("strA");
答案 1 :(得分:0)
这是您正在寻找的非常基本的实现。有很多改进。
/// <summary>
/// Finds the text files that contain paragraph.
/// </summary>
/// <param name="paragraph">The paragraph to check for.</param>
/// <param name="textFilePaths">A list of paths to text files to check.</param>
/// <returns></returns>
List<string> FindFilesWithParagraph(string paragraph, List<string> textFilePaths)
{
List<string> foundPaths = new List<string>(); // list of paths to text files w/ paragraph
foreach (string path in textFilePaths) // iterate through each file
{
if (!File.Exists(path)) // check files actually exist
throw new ArgumentException();
using (var sr = new System.IO.StreamReader(path))
{
if (sr.ReadToEnd().Contains(paragraph)) // read contents of file
foundPaths.Add(path); // and add it to list if it contains the paragraph
}
}
return foundPaths;
}