gpt4 book ai didi

.net - 使用流读取文件时写入文件?

转载 作者:行者123 更新时间:2023-12-02 04:07:34 26 4
gpt4 key购买 nike

我错了一个读取配置文件的函数,但是如果指定了命令行参数“-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字符串可能比当前字符串更长。

最佳答案

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

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

关于.net - 使用流读取文件时写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6888707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com