我有一个字符串,它是 args[0]
。
到目前为止,这是我的代码:
static void Main(string[] args)
{
string latestversion = args[0];
// create reader & open file
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
{
while (sr.Peek() >= 0)
{
// code here
}
}
}
我想检查我的 list.txt
文件是否包含 args[0]
。如果是,那么我将创建另一个进程 StreamWriter
以将字符串 1
或 0
写入文件。我该怎么做?
最佳答案
您是否希望文件特别大?如果没有,最简单的方法就是阅读整篇文章:
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
{
string contents = sr.ReadToEnd();
if (contents.Contains(args[0]))
{
// ...
}
}
或者:
string contents = File.ReadAllText("C:\\Work\\list.txt");
if (contents.Contains(args[0]))
{
// ...
}
或者,您可以逐行阅读:
foreach (string line in File.ReadLines("C:\\Work\\list.txt"))
{
if (line.Contains(args[0]))
{
// ...
// Break if you don't need to do anything else
}
}
或者更像 LINQ:
if (File.ReadLines("C:\\Work\\list.txt").Any(line => line.Contains(args[0])))
{
...
}
请注意,ReadLines
仅在 .NET 4 中可用,但您可以自己在循环中合理轻松地调用 TextReader.ReadLine
。
关于c# - 使用 StreamReader 检查文件是否包含字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6183809/