用流读取文件时写入文件?

时间:2021-02-07 15:38:49

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?

我错误的读取配置文件的函数,但如果指定命令行参数“-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();
                        }
                    }
                }
            }
        }
    }

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.

它有意义为什么它追加到最后,但我想不出任何方式只重写该行,因为IP字符串可能比当前的更长。

1 个解决方案

#1


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:

更简单的方法是读取所有行并替换要替换的行,然后再将新行添加到文件中,如:

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);

#1


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:

更简单的方法是读取所有行并替换要替换的行,然后再将新行添加到文件中,如:

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);