【问题标题】:Writing to a file while reading it with streams?在使用流读取文件时写入文件?
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-01-24
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多