问题描述
我有一个字符串,它是 args[0]
.
I have a string that is 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
写入文件.我该怎么做?
I would like to check if my list.txt
file contains args[0]
. If it does, then I will create another process StreamWriter
to write a string 1
or 0
into the file. How do I do this?
推荐答案
您是否希望文件特别大?如果没有,最简单的方法就是阅读整个内容:
Are you expecting the file to be particularly big? If not, the simplest way of doing it would be to just read the whole thing:
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]))
{
// ...
}
或者,您可以逐行阅读:
Alternatively, you could read it line by line:
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
.
Note that ReadLines
is only available from .NET 4, but you could reasonably easily call TextReader.ReadLine
in a loop yourself instead.
这篇关于使用 StreamReader 检查文件是否包含字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!