0

I have opened a .CSV file in RichTextBox.I added every line's first word to CombobBox items. I want to edit this a specific word and then save it back to the File.

This is how i open the file to 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();
        }

Now i want a Button that finds my comboBox1.Text in richTextBox and replace it with txtbox.Text.

My button looks like this:

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

I would add the method to the end of this button that would save back the text from richTextBox to my .CSV file but this replace method doesnt replace anything in my richTextBox.

My .CSV file (in richTextBox) looks like this:

somestring,somenumber,somespecialcharacters;
somestring2,somenumber2,somespecialcharacters2;

It has about 50 lines,and my combobox is filled with the first words of every line like: "somestring" "somestring2". When i click on somestring (then its my combobox.text) then i write "newstring" to my txtbox.text. When i click my button it should find comboBox.text in richtxt and replace it with my txtbox.text.

Any ideas why it doesnt work?

Tamas555
  • 47
  • 10

3 Answers3

1

You wrote:

but this replace method doesnt replace anything in my richTextBox.

This is because strings in C# are immutable? Whatever you do to strings, the original string is never changed. The result is always in a new string.

See Why .NET String is immutable?

So although your code changes the value of str, the original str that your richtextbox displays is not changed.

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

str refers to a new string. RichTextBox1.Text still refers to the original string.

Solution: Assign the new string to the rich text box:

this.RichTextBox1.Text = str;

If you want to save the text in a file you'll have to create a FileWriter that will write the new string (not the changed string, strings can't change!).

Depending on how important it is that you don't lose the old file in case of problems, consider using a tmpfile to write, delete the original and move the tmpfile

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • So now I added your solution code but it still doesn't change the text in richTextBox. – Tamas555 Aug 09 '17 at 14:30
  • And you really checked the changed string in the debugger and you saw that it was changed correctly? – Harald Coppoolse Aug 09 '17 at 14:34
  • Yes i checked it. – Tamas555 Aug 09 '17 at 17:15
  • Interesting. So the first time richtextbox1.Text = str shows the correct text, but the second time it doesn't work? I guess there is some error. Did you try rictextBox1.Text = "Hello World1" instead? And what happens if you try str = "Hello World"; richtextBox1.Text = str? Be creative in diagnosing your problems, don't wait for answers from others – Harald Coppoolse Aug 10 '17 at 06:29
  • Thats why this forum is for. I tried them already. i can give the textbox what should it write but the maximum was the textbox cleared all the text and shown only the changed word! – Tamas555 Aug 11 '17 at 19:41
  • `FileWriter` doesn't work as welll - Use `File.WriteAllText` – Momoro Nov 01 '19 at 05:39
  • Hmm, maybe the problem is that your are referencing the `ComboBox`, rather than literally using it? I dunno :D – Momoro Nov 01 '19 at 05:43
0

In order to replace or delete something using a stream reader, you will need to delete every line and replace it with a new (temporary) file.

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.
Freek W.
  • 406
  • 5
  • 20
  • Thats a little bit chineese for me.. I'm begginer with programming. But where is the replace method in you code? And what is this ID? Btw i made a mistake,my lines doesn't end with " ; " they're ends with only enter. Also i want to read the richTextBox.text not the file because the file is already opened in the richTextBox,it would be easier for me due to my programming language is kinda bad yet. – Tamas555 Aug 09 '17 at 14:20
  • Added some commentary, as for the identifier, (or ID) its usually the Primary Key in what is usually a database. So you should have something to compare a line with so it knows what line it is. It can also be an attribute. (for instance date or age). EDIT: This is some of my old code but I decided to post it in its entirety so it might help you later along the lines when you want to delete (because replacing is much simpler). This method can do both. – Freek W. Aug 09 '17 at 14:21
  • Can i do it easier with only the richTextBox.Text without giving the file path? because the file path is not fixed,as you could se i use openfiledialog in anothed method to open a file.I would want to open the file in richtextbox,edit the richtextbox and then save back. I can already open a file and i can save it back from richtextbox but I can't do the editing part of it. – Tamas555 Aug 09 '17 at 14:27
  • Use 'ofd.FileName' as your path – Freek W. Aug 09 '17 at 14:31
  • Use `File.WriteAllLines(ofd.FileName, richTextBox1.Text)` – Freek W. Aug 09 '17 at 14:49
  • But ofd.Filename is in another method.. (File open) How could i add this to a button click method..? – Tamas555 Aug 09 '17 at 17:16
  • Okay, Tamas555, I see what you need. Create a `public static string file = " ";` , and when the user opens the file, do this: `file = ofd.FileName;` - That should do it :) – Momoro Nov 01 '19 at 05:45
0

On second notice, check out this code:

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

I think this is more in line with what you had in mind?

Freek W.
  • 406
  • 5
  • 20
  • Your save button just saved my file with this in it: "{\rtf1\ansi\ansicpg1250\deff0\deflang1038{\fonttbl{\f0\fnil\fcharset238 Microsoft Sans Serif;}} \viewkind4\uc1\pard\f0\fs17\par } NULL " – Tamas555 Aug 09 '17 at 17:07
  • it loads it without that though (its the format of the text). if you're trying to use the textfile like a database use the code below instead. – Freek W. Aug 10 '17 at 09:11