2011-07-31 22 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

簡単な方法は次のように再びファイルに新しい行を追加し、その後、すべての行を読んで、置き換えたい行(複数可)を交換することである:それは私がupvoteせません

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することができますbtw! :D –

関連する問題