StreamWriter在文件末尾在新线路上添加了额外的字符

发布于 2025-01-24 18:04:05 字数 1563 浏览 2 评论 0原文

我正在尝试使用FileStream和StreamReader / streamWriter在C#中修改.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” 之外,我没有任何编写其他字符串的问题。该字符串是唯一引起我刚刚描述的问题的字符串。它似乎是从最后一行中抓住字符,例如rlayerMulti_layer中。

例如:这

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

变成了

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

Ex 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

以下替换流wr的部分似乎解决了问题,但是我试图弄清为什么使用StreamWriter无法正常工作。

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

I'm trying to modify an .ini file, in C# with .NET 5.0, using FileStream and StreamReader / StreamWriter. I just need to modify the first line of the file so I read the entire file into a list of strings called strList, modify the first line, and then write it all back to the same file.

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

The issue I'm running into is that I'll have new character(s) at the end of my file on new line(s). I verified that the number of lines I read from the file matches what is in the file and that the for loop only writes that same number of lines back into the file. I don't have any issues writing other strings except for "test01". This string is the only one that causes the issue that I just described. It seems to be grabbing characters from the last line like R or LAYER from MULTI_LAYER.

Ex 1: This

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

Becomes this

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

Ex 2: This

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

Becomes this

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

Replacing the StreamWriter portion with the following seems to fix the issue but I'm trying to figure out why using StreamWriter doesn't work as I expect it to.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮凉 2025-01-31 18:04:05

这是因为您使用file.openwritedocumentation

OpenWrite方法如果已经存在文件路径,则打开一个文件,或者如果不存在,则可以创建新文件。对于现有文件,它不会将新文本附加到现有文本。相反,它用新字符覆盖现有字符。如果您用较短的字符串(例如“第二行”)覆盖更长的字符串(例如“这是openwrite方法的测试”),则文件将包含字符串的组合( “ openwrite方法的第二个运行测试”)。

虽然您可以更改代码可以使用file.create,但我建议更明显地更改代码 - 不仅是写作,而是阅读:

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

那是< em>多更简单的代码来执行同样的事情。

两者之间的中途房屋将是使用file.opentext(返回streamWriter)和file.createText(要返回StreamWriter)。无需自己包裹。

This is because you're using File.OpenWrite. From the remarks in the 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").

While you could just change your code to use File.Create instead, I'd suggest changing the code more significantly - not just the writing, but the reading too:

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

That's much simpler code to do the same thing.

The half-way house between the two would be to use File.OpenText (to return a StreamWriter) and File.CreateText (to return a StreamWriter). There's no need to do the wrapping yourself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文