2011-09-01 83 views
1

如何跳過包含行開頭的分號的文本文件中的行?我目前正在閱讀服務器名稱正常工作的文本文件。如果服務器正在進入維護模式,我想在一行的起始處添加一個分號以將其註釋掉。在文本文件中跳過包含分號的行

+0

你目前的代碼是什麼? –

+0

在什麼情況下?如果第一個字符是';',則只能在該行中閱讀並且不執行任何操作,但只有在上下文允許的情況下才能執行。 – mydogisbox

+0

這麼討厭,在我回答之前已經有6個答案了.. –

回答

2
var lines = File.ReadAllLines(path); 
foreach(var line in lines) 
{ 
    if(line.StartsWith(";")) 
    { 
     continue; 
    } 
    else 
    { 
     // do your stuff 
    } 
} 
+0

謝謝大家。 BioBuckyBall,我不認爲使用「繼續」選項。我正在玩「startswith」功能,但我想我有一個大腦放屁。 – Dovey

1

編輯:好的,所以我們可以使它更容易些......

foreach (var currentLine in File.ReadAllLines(@"C:\somefile.txt")) 
{ 
    if (currentLine.StartsWith(";")) continue; 

    // Pretend this is the function you want to do below. 
    ProcessLine(currentLine); 
} 
1
if (!textline.StartsWith(";")) 
    // do something 
0
foreach(string line in readLines()) 
{ 
    if (line[0] == ';') continue; 
    ... 
} 
+0

再次感謝大家。你幫了我很大的忙,給了我幾個可行的選擇。 – Dovey

1

您使用的東西,從System.IO.TextReader你可以Peek派生的下一個字符,看假設如果它是分號。否則,請閱讀該行並檢查字符串的第一個字符。

1

試試這個:

 var allLines = System.IO.File.ReadAllLines("SOME-PATH"); 
     var filteredLines = from l in allLines 
      where !l.StartsWith(";") 
     select l; 
0

也許StartWith將有助於

string line = null; 
using (System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt")) 
{ 
    while ((line = file.ReadLine()) != null) 
    { 
     if (!line.StartsWith(";")) 
     { 
      // do thomething 
     } 
    } 
} 
1

我明白你問的C#這個問題。

在這種情況下,你可以從字符串類使用startswith,我不知道怎麼是你的代碼,但我認爲這可以幫助你:

using System; 
using System.IO; 

class Program { 
    static void Main(string[] args) { 
     string filePath = @"test.txt"; 
     string line; 
     string fileContent = ""; 

     if (File.Exists(filePath)) { 
      StreamReader file = null; 
      try { 
       file = new StreamReader(filePath); 
       while ((line = file.ReadLine()) != null) { 
         if (!line.StartsWith(";")){ 
           Console.WriteLine(line); 
           fileContent += line;   
         } 
       } 
      } finally { 
       if (file != null) 
        file.Close(); 
      } 
     } 
    } 
} 
} 
0
在.NET 4.0中

File.ReadLines("c:\test.txt").Where(x => !x.StartsWith(";")); 

也許你想進行AsParallel

File.ReadLines("c:\test.txt").AsParallel().Where(x => !x.StartsWith(";")); 

;)

相關問題