在文本文件中所做的更改(以程序方式)不会反映回来



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

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

while循环中存在错误。

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

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

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

相关内容

最新更新