Writing to a file while reading it with streams?
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
{
s开发者_运维问答tring[] 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.
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:
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);
精彩评论