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字符串可能比目前的時間長一些。
它不會讓我給予好評,但這很好,謝謝。 –
不客氣,順便說一句,現在你可以upvote! :d –