我有一个字符串是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
or 0
到文件中。我该怎么做呢?
您预计该文件会特别大吗?如果没有,最简单的方法就是阅读全文:
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]))
{
// ...
}
或者,您可以逐行阅读:
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
而是自己循环。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)