【问题标题】:Changes made in text file (programatically ) are not reflected back文本文件中所做的更改(以编程方式)不会反映回来
【发布时间】:2013-07-09 17:38:24
【问题描述】:

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

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

【问题讨论】:

    标签: c#-3.0


    【解决方案1】:

    错误出现在您的 while 循环中。

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

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

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

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 2013-02-07
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 2022-09-11
      相关资源
      最近更新 更多