StreamWriter 在文件末尾的新行上添加额外的字符

StreamWriter adds extra character(s) on new line(s) at the end of file

我正在尝试使用 FileStream 和 StreamReader / StreamWriter 在 C# 中使用 .NET 5.0 修改 .ini 文件。我只需要修改文件的第一行,所以我将整个文件读入一个名为 strList 的字符串列表,修改第一行,然后将其全部写回同一个文件。

List<string> strList = new List<string>();

using (FileStream fs = File.OpenRead(@"C:\MyFolder\test.ini"))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        while (!sr.EndOfStream)
        {
            strList.Add(sr.ReadLine());
        }
    }
}

strList[0] = "test01";

using (FileStream fs = File.OpenWrite(@"C:\MyFolder\test.ini"))
{
    using (StreamWriter sw = new StreamWriter(fs))
    {
        for (int x = 0; x < ewsLines.Count; x++)
        {          
            sw.WriteLine(strList[x]);            
        }
    }
}

我 运行 遇到的问题是我将在文件末尾换行添加新字符。我验证了我从文件中读取的行数与文件中的内容相匹配,并且 for 循环只将相同数量的行写回到文件中。除了 "test01" 之外,我在编写其他字符串时没有任何问题。这个字符串是唯一导致我刚才描述的问题的字符串。它似乎是从最后一行抓取字符,例如 RLAYER 来自 MULTI_LAYER.

示例 1:这个

S10087_U1
Cq4InEq=TRUE
XtrVer=5.5
IOCUPDATEMDB=TRUE
ARCHITECTURE=MULTI_LAYER

变成这样

test01
Cq4InEq=TRUE
XtrVer=5.5
IOCUPDATEMDB=TRUE
ARCHITECTURE=MULTI_LAYER
R

例 2:这个

test01 - Copy
Cq4InEq=TRUE
XtrVer=5.5
IOCUPDATEMDB=TRUE
ARCHITECTURE=MULTI_LAYER
ER

变成这样

test01
Cq4InEq=TRUE
XtrVer=5.5
IOCUPDATEMDB=TRUE
ARCHITECTURE=MULTI_LAYER
LAYER

用以下内容替换 StreamWriter 部分似乎可以解决问题,但我想弄清楚为什么使用 StreamWriter 不能像我预期的那样工作。

File.WriteAllLines(@"C:\MyFolder\test.ini", strList);

这是因为您正在使用 File.OpenWrite。来自documentation中的评论:

The OpenWrite method opens a file if one already exists for the file path, or creates a new file if one does not exist. For an existing file, it does not append the new text to the existing text. Instead, it overwrites the existing characters with the new characters. If you overwrite a longer string (such as "This is a test of the OpenWrite method") with a shorter string (such as "Second run"), the file will contain a mix of the strings ("Second runtest of the OpenWrite method").

虽然您 可以 只更改您的代码以使用 File.Create,但我建议更显着地更改代码 - 不仅是写作,还有阅读:

string path = @"C:\MyFolder\test.ini";
var lines = File.ReadAllLines(path);
lines[0] = "test01";
File.WriteAllLines(path, lines);

这是很多更简单的代码来做同样的事情。

两者之间的half-way房子是用File.OpenText(对return一个StreamWriter)和File.CreateText(对return一个StreamWriter)。无需自己包裹。