c# - 使用 StreamReader 检查文件是否包含字符串

标签 c# string file-io

我有一个字符串,它是 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 以将字符串 10 写入文件。我该怎么做?

最佳答案

您是否希望文件特别大?如果没有,最简单的方法就是阅读整篇文章:

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/

相关文章:

c# - 无法在 Visual Studio 2010 中加载文件或程序集

c# - 最大化控制台窗口 - C#

c# - 带有复选框 where 条件组合的 linq to sql 查询

java - Java中计算两个字符串之间的误差

c# - Linq System.OutofMemoryException 异常

c++ - 将字符串转换为 char* 问题

c - 如何从用户空间 C 读取内核模块 (/dev) 文件

c - 获取硬盘的簇大小(通过代码)

c++ - 以理智、安全和有效的方式复制文件

PHP 字符串连接(一个来自变量,另一个来自三元运算符)给出意想不到的结果