22

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?

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
jeremychan
  • 4,309
  • 10
  • 42
  • 56

4 Answers4

38

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • why not just - string contents = File.ReadAllLines("c:\\work\\list.txt"); – Andrew May 31 '11 at 06:44
  • @Andrew: Well that wouldn't compile :) But you can use `File.ReadAllText`, which I've given as another alternative. If you're going to read everything in one go, you might as well do that - but if you need to read it line by line (to save memory) then `ReadLines` is more efficient. – Jon Skeet May 31 '11 at 06:46
  • @VMAtm: Which code? I've given several options. Note that the `ReadLines` option will only read as far as the first line containing the text. – Jon Skeet May 31 '11 at 06:47
  • Also there is a little bug in the first example. That semicolon happens to me, too! – Bitterblue Dec 05 '13 at 14:26
  • in the LINQ example, the ")" is missing :-) – Muflix Dec 02 '16 at 12:21
  • The if (File.ReadLines("C:\\Work\\list.txt").Any(line => line.Contains(args[0]))) option is what I'm looking for with something to have a one liner I can add to an existing if check but isn't. After the Any the second line. is failing as it's saying Contains is not an option which the context sensitive help confirms. – John Dec 03 '20 at 19:57
  • @John: I'm afraid I don't understand what you mean by "with something to have a one liner I can add to an existing if check but isn't". Please ask a new question with a [mcve]. – Jon Skeet Dec 03 '20 at 20:21
  • Thanks for replying Jon. When I use your single LINQ-like line above I start typing in File.ReadLines("C:\list.txt").Any(line => line. Then try typing in Contains but it's not an option to enter Contains and complains. – John Dec 03 '20 at 20:50
  • Nevermind. I have no idea why but now it's validating. – John Dec 03 '20 at 20:52
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");
            }
    }   
    
VMAtm
  • 27,943
  • 17
  • 79
  • 125
  • 1
    Your `line.Length > 0` condition should be `line != null` - otherwise you'll stop on the first blank line *or* throw an exception when you reach the end of the file. Also, your first bit writes a 1 or 0 *for every line* of the input file; I don't think that's required. – Jon Skeet May 31 '11 at 06:49
0
if ( System.IO.File.ReadAllText("C:\\Work\\list.txt").Contains( args[0] ) )
{
...
}
ibram
  • 4,414
  • 2
  • 22
  • 34
0

The accepted answer reads all file in memory which can be consuming.

Here's an alternative inspired by VMAtm answer

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;
Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149