Using StreamReader to check if a file contains a string

后端 未结 3 869
执念已碎
执念已碎 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条回答
  •  旧时难觅i
    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");
              }
      }   
      

提交回复
热议问题