使用StreamReader检查文件是否包含某个字符串

22

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

我想检查我的list.txt文件是否包含args[0]。 如果是,则我将创建另一个进程StreamWriter来将字符串10写入文件中。 我该如何操作?

4个回答

38

您是否期望文件特别大?如果不是,最简单的方法就是读取整个文件:

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来实现相同的功能。

为什么不直接使用以下代码 - string contents = File.ReadAllLines("c:\work\list.txt"); - Andrew
@Andrew:那不会编译 :) 但你可以使用File.ReadAllText,我已经提供了另一个选择。如果你要一次读取所有内容,那么最好这样做 - 但是如果你需要逐行读取(为了节省内存),那么ReadLines更高效。 - Jon Skeet
@VMAtm:哪段代码?我给出了几个选项。请注意,“ReadLines”选项只会读取包含文本的第一行。 - Jon Skeet
第一个示例中也有一个小错误。分号也发生在我的代码中! - Bitterblue
在LINQ示例中,缺少 ")" :-) - Muflix
显示剩余4条评论

4
  1. You should not add the ';' at the end of the using statement.
  2. Code to work:

    string latestversion = args[0];
    
    using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
    using (StreamWriter sw = new StreamWriter("C:\\Work\\otherFile.txt"))
    {
            // loop by lines - for big files
            string line = sr.ReadLine();
            bool flag = false;
            while (line != null)
            {
                if (line.IndexOf(latestversion) > -1)
                {
                    flag = true;
                    break;
                }
                line = sr.ReadLine();
            }
            if (flag)
                sw.Write("1");
            else
                sw.Write("0");
    
            // other solution - for small files
            var fileContents = sr.ReadToEnd();
            {
                if (fileContents.IndexOf(latestversion) > -1)
                    sw.Write("1");
                else
                    sw.Write("0");
            }
    }   
    

1
你的 line.Length > 0 条件应该是 line != null - 否则当你到达文件结尾时,会停留在第一行空白行 或者 抛出异常。此外,你的第一个代码块会为输入文件的每一行写入1或0;我认为这不是必需的。 - Jon Skeet

0
if ( System.IO.File.ReadAllText("C:\\Work\\list.txt").Contains( args[0] ) )
{
...
}

0

被接受的答案将所有文件读入内存,这可能会消耗大量资源。

以下是受VMAtm答案启发的替代方案。

using (var sr = new StreamReader("c:\\path\\to\\file", true))
    for (string line; (line = sr.ReadLine()) != null;) //read line by line
        if (line.Contains("mystring"))
            return true;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接