Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c# - Using StreamReader to check if a file contains a string

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 it does, then I will create another process StreamWriter to write a string 1 or 0 into the file. How do I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...