【问题标题】:Read textfile and show it in richtextbox. Show one word from Richtextbox in ComboBox then find it in text and replace it with TextBox.text读取文本文件并在richtextbox 中显示。在 ComboBox 中显示 Richtextbox 中的一个单词,然后在文本中找到它并用 TextBox.text 替换它
【发布时间】:2018-01-17 10:16:19
【问题描述】:

我在 RichTextBox 中打开了一个 .CSV 文件。我将每行的第一个单词添加到 CombobBox 项目中。我想编辑这个特定的单词,然后将其保存回文件。

这就是我打开文件到richTextBox1的方式。

        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "Csv files (.csv)|*.csv";
        ofd.Title = "Open a file...";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            StreamReader sr = new StreamReader(ofd.FileName);
            richTextBox1.Text = sr.ReadToEnd();
        }

现在我想要一个在richTextBox 中找到我的comboBox1.Text 并将其替换为txtbox.Text 的按钮。

我的按钮如下所示:

        private void button1_Click(object sender, EventArgs e)
        {
            using (TextReader reader = new StringReader(richTextBox1.Text))
            {
                string str = reader.ReadToEnd();
                string cbtxt = comboBox1.Text;
                string tbtxt = txtbox.Text;
                str = str.Replace(cbtxt, tbtxt);
            }
        }

我会将方法添加到此按钮的末尾,该方法会将文本从richTextBox 保存回我的 .CSV 文件,但此替换方法不会替换我的richTextBox 中的任何内容。

我的 .CSV 文件(在 RichTextBox 中)如下所示:

一些字符串,一些数字,一些特殊字符;
somestring2,somenumber2,somespecialcharacters2;

它有大约 50 行,我的组合框充满了每一行的第一个单词,例如:“somestring”“somestring2”。 当我单击某个字符串(然后是我的combobox.text)时,我将“newstring”写入我的txtbox.text。当我单击我的按钮时,它应该在richtxt 中找到comboBox.text 并将其替换为我的txtbox.text。

任何想法为什么它不起作用?

【问题讨论】:

  • 您是否将 str 中的文本放入richTextBox1.Text 中?我在代码中没有看到这个。
  • 替换不行吗?如果不是我如何用保持不变的文本替换文本?

标签: c# string winforms replace richtextbox


【解决方案1】:

你写道:

但这个替换方法不会替换我的richTextBox 中的任何内容。

这是因为 C# 中的字符串是不可变的?无论您对字符串做什么,原始字符串都不会改变。结果总是在一个新的字符串中。

See Why .NET String is immutable?

因此,尽管您的代码更改了str 的值,但您的richtextbox 显示的原始str 并未更改。

string str = reader.ReadToEnd();
string cbtxt = comboBox1.Text;
string tbtxt = txtbox.Text;
str = str.Replace(cbtxt, tbtxt);

str 指的是一个新的字符串。 RichTextBox1.Text 仍然引用原始字符串。

解决方案:将新字符串分配给富文本框:

this.RichTextBox1.Text = str;

如果要将文本保存在文件中,则必须创建一个 FileWriter 来写入新字符串(不是更改的字符串,字符串不能更改!)。

根据在出现问题时不丢失旧文件的重要性,考虑使用 tmpfile 写入、删除原始文件和移动 tmpfile

【讨论】:

  • 所以现在我添加了您的解决方案代码,但它仍然不会更改richTextBox 中的文本。
  • 您真的在调试器中检查了更改后的字符串,您看到它已正确更改?
  • 是的,我查过了。
  • 有趣。所以第一次richtextbox1.Text = str显示正确的文字,第二次就不行了?我想有一些错误。您是否尝试 rictextBox1.Text = "Hello World1" 代替?如果你尝试 str = "Hello World"; 会发生什么?富文本框1.Text = str?创造性地诊断你的问题,不要等待别人的答案
  • 这就是这个论坛的目的。我已经试过了。我可以给文本框它应该写什么,但最大的是文本框清除了所有文本并只显示更改的单词!
【解决方案2】:

为了使用流阅读器替换或删除某些内容,您需要删除每一行并将其替换为新的(临时)文件。

var tempFile = Path.GetTempFileName(); //Creates temporary file
            List<string> linesToKeep = new List<string>(); //Creates list of all the lines you want to keep (everything but your selection)
            using (FileStream fs = new FileStream(path(), FileMode.Open, FileAccess.Read)) //(this opens a new filestream (insert your path to your file there)
            {
                using (StreamReader sr = new StreamReader(fs)) //here is starts reading your file line by line.
                {
                    while (!sr.EndOfStream) //as long it has not finished reading
                    {
                        string currentline = sr.ReadLine().ToString(); //this takes the current line it has been reading
                        string splitline = currentline; //this is a temporary string because you are going to have to split the lines (i think you have 3 so split in "," and then index the first line (your identifier or name)))
                        if (splitline.Split(';')[0] != ID) //split the line and add your personal identifier so it knows what to keep and what to delete.
                        {
                            linesToKeep.Add(currentline); //adds the line to the temporary file list of line that you want to keep
                        }
                    }
                }
            }
            File.WriteAllLines(tempFile, linesToKeep); //writes all the lines you want to keep back into a file
            File.Delete(path()); //deletes the old file
            File.Move(tempFile, path()); //moves temporary file to old location of the old file.

【讨论】:

  • 这对我来说有点中国化。我是编程初学者。但是代码中的替换方法在哪里?这个ID是什么?顺便说一句,我犯了一个错误,我的行不以“;”结尾,它们只以 enter 结尾。另外我想读取richTextBox.text而不是文件,因为文件已经在richTextBox中打开了,因为我的编程语言有点糟糕,所以对我来说会更容易。
  • 添加了一些注释,至于标识符(或 ID),它通常是数据库中的主键。所以你应该有一些东西来比较一条线,所以它知道它是什么线。它也可以是一个属性。 (例如日期或年龄)。编辑:这是我的一些旧代码,但我决定将其完整发布,以便稍后在您想要删除时帮助您(因为替换更简单)。这种方法可以两者兼得。
  • 我可以只使用richTextBox.Text 而不提供文件路径更容易吗?因为文件路径不固定,你可以看到我在另一种方法中使用openfiledialog打开文件。我想在richtextbox中打开文件,编辑richtextbox然后保存回来。我已经可以打开一个文件,我可以将它从 Richtextbox 中保存回来,但我无法对其进行编辑。
  • 使用 'ofd.FileName' 作为你的路径
  • 使用File.WriteAllLines(ofd.FileName, richTextBox1.Text)
【解决方案3】:

第二次通知,查看此代码:

private void btnLoad_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        richTextBox1.LoadFile(ofd.FileName);
    }
}

private void btnSave_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        richTextBox1.SaveFile(ofd.FileName);
    }
}

我觉得这更符合你的想法?

【讨论】:

  • 您的保存按钮刚刚保存了我的文件,其中包含以下内容:“{\rtf1\ansi\ansicpg1250\deff0\deflang1038{\fonttbl{\f0\fnil\fcharset238 Microsoft Sans Serif;}} \viewkind4 \uc1\pard\f0\fs17\par } NULL "
  • 它会在没有它的情况下加载它(它的文本格式)。如果您尝试像数据库一样使用文本文件,请改用下面的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
相关资源
最近更新 更多