在使用流读取文件的同时写入文件?
我错误地读取配置文件的函数,但如果指定了命令行参数“-ip xxxx”,我想覆盖配置文件中的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 字符串可能比当前的长度长。
I wrong a function to read a configuration file, but if the command line arguement "-ip x.x.x.x" is specified, I want to overwrite the IP setting in the configuration file. I am using the following code which reads fine, but appends my new line to the end. How can I have it rewrite the line it is reading?
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();
}
}
}
}
}
}
It makes sense why it appends to the end, but I can't think of any way to just rewrite the line, since the IP string might be longer than what is currently there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种更简单的方法是读取所有行并替换要替换的行,然后再次将新行追加到文件中,如下所示:
An easier way is to read all the lines and replace the line(s) you want to replace, then append the new lines to file again like: