Using StreamReader to check if a file contains a s

2019-01-15 06:12发布

问题:

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?

回答1:

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.



回答2:

  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");
            }
    }   
    


回答3:

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