0

我有以下代码。在我打开文件时对文本文件进行更改时,我看不到任何更改,实际上文本文件的文本已被删除。

private void btnGo_Click(object sender, EventArgs e)
    {
        string content;

        string newword = "Tanu";
        string oldword = "Sunrise";
        System.IO.StreamReader file =
           new System.IO.StreamReader(txtFilePath.Text);

        while ((content = file.ReadLine()) != null)
        {
            if (content == "Project name = Sunrise ")
            {
                string newtxt = Regex.Replace(content, oldword, newword);
                content = content.Replace(content, newtxt);
            }
           // counter++;
        }

        file.Close();

        using (StreamWriter writer = new StreamWriter(txtFilePath.Text))
        {
            writer.Write(content);

            writer.Close();
4

1 回答 1

0

错误在您的 while 循环中。

while ((content = file.ReadLine()) != null)

在用 newtxt 替换内容后,while 再次执行并尝试读取文件中将内容设置为 null 的下一行,因此当您退出 while 循环时,您的内容为 null。

尝试将文件内容读入不同的变量或使用 newtxt 本身写入文件。

于 2013-07-09T17:53:37.193 回答