使用StreamReader检查文件是否包含字符串

我有一个字符串是args[0]

这是我的代码到目前为止:

 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 } } } 

我想检查我的list.txt文件是否包含args[0] 。 如果我有,那么我将创建另一个进程StreamWriter将字符串1写入文件,或者将0写入文件。 我该怎么做?

你期待文件特别大吗? 如果没有,最简单的方法就是阅读整个内容:

 using (StreamReader sr = new StreamReader("C:\\Work\\list.txt")) { string contents = sr.ReadToEnd(); if (contents.Contains(args[0])) { // ... } } 

要么:

 string contents = File.ReadAllText("C:\\Work\\list.txt"); if (contents.Contains(args[0])) { // ... } 

或者,您可以逐行阅读:

 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 } } 

或者甚至更像LINQ:

 if (File.ReadLines("C:\\Work\\list.txt").Any(line => line.Contains(args[0]))) { ... } 

请注意, ReadLines仅适用于.NET 4,但您可以自己在循环中轻松调用TextReader.ReadLine

  1. 你不应该添加’;’ 在using语句的末尾。
  2. 工作代码:

     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"); } } 
 if ( System.IO.File.ReadAllText("C:\\Work\\list.txt").Contains( args[0] ) ) { ... }