【发布时间】:2011-10-16 20:26:54
【问题描述】:
我错了一个读取配置文件的函数,但是如果指定了命令行参数“-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 字符串可能比当前存在的要长。
【问题讨论】:
标签: .net filestream streamreader streamwriter