Using StreamReader to check if a file contains a string

后端 未结 3 864
执念已碎
执念已碎 2020-12-06 10:10

I have a string that is args[0].

Here is my code so far:

static void Main(string[] args)
{
    string latestversion = args[0];
    // cr         


        
相关标签:
3条回答
  • 2020-12-06 10:25
    if ( System.IO.File.ReadAllText("C:\\Work\\list.txt").Contains( args[0] ) )
    {
    ...
    }
    
    0 讨论(0)
  • 2020-12-06 10:37

    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.

    0 讨论(0)
  • 2020-12-06 10:38
    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");
              }
      }   
      
    0 讨论(0)
提交回复
热议问题