我正在文本文件(也包括 XML)中搜索字符串。这是我首先想到的:
using (StreamReader sr = File.OpenText(fileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mySpecialString"))
return true;
}
}
return false;
我想逐行阅读以尽量减少使用的 RAM 量。找到字符串后,它应该中止操作。我不将其作为 XML 处理的原因是因为它必须被解析并且还会在必要时消耗更多内存。
另一个简单的实现是
bool found = File.ReadAllText(path).Contains("mySpecialString") ? true : false;
但这会将整个文件读入内存,这不是我想要的。另一方面,它可能会提高性能。
另一个是这个
foreach (string line in File.ReadLines(path))
{
if (line.Contains("mySpecialString"))
{
return true;
}
}
return false;
但其中哪一个(或您的另一个?)内存效率更高?
最佳答案
您可以使用查询 File.ReadLines
,因此它只读取所需的行数以满足您的查询。 Any()
方法将在遇到包含您的字符串的行时停止。
return File.ReadLines(fileName).Any(line => line.Contains("mySpecialString"));
关于c# - 读取文本文件并以内存有效的方式搜索字符串(并在找到时中止),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30078432/