2011-07-31 41 views
3

我錯了一個讀取配置文件的函數,但是如果指定了命令行參數「-ip x.x.x.x」,我想覆蓋配置文件中的IP設置。我正在使用下面的代碼,它可以很好地讀取,但將我的新行添加到最後。我怎麼能重寫它正在閱讀的行?在使用流讀取文件時寫入文件?

private static void ParsePropertiesFile(string file) 
    { 
     using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite)) 
     { 
      StreamReader sr = new StreamReader(fs); 
      StreamWriter sw = new StreamWriter(fs); 

      string input; 

      while ((input = sr.ReadLine()) != null) 
      { 
       // SKIP COMMENT LINE 
       if (input.StartsWith("#")) 
       { 
        continue; 
       } 
       else 
       { 
        string[] line; 
        line = input.Split('='); 

        if (line[0] == "server-ip") 
        { 
         // If IP was not specified in the Command Line, use this instead 
         if (ServerSettings.IP == null) 
         { 
          // If the setting value is not blank 
          if (line[1] != null) 
          { 
           ServerSettings.IP = IPAddress.Parse(line[1]); 
          } 
         } 
         else 
         { 
          sw.("--REPLACE_TEST--"); 
          sw.Flush(); 
         } 
        } 
       } 
      } 
     } 
    } 

這是有道理的,爲什麼它追加到了最後,但我想不出任何辦法,只是重寫線,因爲IP字符串可能比目前的時間長一些。

回答

1

更簡單的方法是閱讀所有的線路和更換線(S)要替換,然後追加新行再如文件:

string[] lines = File.ReadAllLines("Your file path"); 

for (int lineIndex = 0; lineIndex < lines.Length; lineIndex++) 
{ 
    if (/*if we want to modify this line..*/) 
    { 
     lines[lineIndex] = "new value"; 
    } 
} 

File.AppendAllLines(lines); 
+0

它不會讓我給予好評,但這很好,謝謝。 –

+0

不客氣,順便說一句,現在你可以upvote! :d –