2011-05-31 139 views
15

我有一個字符串,它是args[0]使用的StreamReader來檢查文件是否包含字符串

這裏是我到目前爲止的代碼:

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寫入該文件。我該怎麼做?

+1

多大的文件? – 2011-05-31 06:35:10

+0

大小約爲69kb – jeremychan 2011-05-31 06:36:42

回答

26

您是否期待文件特別大?如果沒有,這樣做的最簡單的方法是將剛讀了整個事情:

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

+0

爲什麼不只是 - 字符串內容= File.ReadAllLines(「c:\\ work \\ list.txt」); – Andrew 2011-05-31 06:44:41

+1

這段代碼可能對大文件很慢 – VMAtm 2011-05-31 06:46:34

+0

@Andrew:那不會編譯:)但是你可以使用'File.ReadAllText',這是我給出的另一種選擇。如果您要一口氣讀取所有內容,那麼您可能會這麼做 - 但如果您需要逐行讀取(以節省內存),那麼「ReadLines」效率更高。 – 2011-05-31 06:46:49

0
if (System.IO.File.ReadAllText("C:\\Work\\list.txt").Contains(args[0])) 
{ 
... 
} 
3
  1. 你不應該添加 ';'在使用說明結束時。
  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"); 
         } 
    } 
    
+1

你的'line.Length> 0'條件應該是'line!= null' - 否則你會停在第一個空行*或*當你到達文件末尾時拋出一個異常。此外,您的第一位爲輸入文件的每行*寫入1或0 *我不認爲這是必需的。 – 2011-05-31 06:49:00

+0

感謝您的支持 – VMAtm 2011-05-31 06:53:54

相關問題