使用StreamReader检查文件是否包含字符串 [英] Using StreamReader to check if a file contains a string
问题描述
我有一个字符串是 args [0]
这是我的代码: (b
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'
//创建读取器&打开文件
(StreamReader sr = new StreamReader(C:\\Work\\list.txt)); (sr.Peek()> = 0)
{
// code here
}
}
} $
{
我想查看我的 list.txt
文件包含 args [0]
。如果我有,然后我将创建另一个进程 StreamWriter
写一个字符串 1
到文件中,或写 0
到文件中。我怎么做到的?
您是否期望文件特别大?如果不是这样,最简单的方法就是读取整个文件:
$ $ $ $ $ $ $ $ $ code $>使用(StreamReader sr = new StreamReader C:\\Work\\list.txt))
{
string contents = sr.ReadToEnd();
if(contents.Contains(args [0]))
{
// ...
}
}
或者:
$ p $ 字符串内容=文件。 ReadAllText( C:\\Work\\list.txt);
$ p
if(contents.Contains(args [0]))
{
// ...
}
$ b
另外,你也可以一行一行阅读:
foreach (C:\\Work\\list.txt))
{
if(line.Contains(args [0]))
{
// ...
//如果您不需要做其他事情,请打破
}
}
甚至更像LINQ: 请注意
$ b $ pre $ if .ReadLines(C:\\Work\\list.txt)。any(line => line.Contains(args [0])))
中自行调用。
{
...
$ / code> ReadLines
仅适用于.NET 4,但是您可以自己轻松地在
i have a string that is args[0]
here is my code so far:
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
}
}
}
I would like to check if my list.txt
file contains args[0]
. If I have, then I will create another process StreamWriter
to write a string 1
into the file, or write 0
into the file. How do i do it?
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]))
{
// ...
}
}
Or:
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
}
}
Or even more LINQ-like:
if (File.ReadLines("C:\\Work\\list.txt").Any(line => line.Contains(args[0])))
{
...
}
Note that ReadLines
is only available from .NET 4, but you could reasonably easily call TextReader.ReadLine
in a loop yourself instead.
这篇关于使用StreamReader检查文件是否包含字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!