Kratos
Kratos

Reputation: 205

how to replace a word in a text file without overwriting the whole file

i am reading a textfile and storing the read data in the textboxes in my form. now i want that if a user makes any change in the data in the textboxes it should be reflected in the textfile. i have tried the following thing, but the problem is that is replaces the whole file with the single line.

switch (match.Groups["key"].Value)
                        {
                            case "type": if (textBox1.Text != match.Groups["value"].Value)
                                { File.WriteAllText(path.ToString(),Regex.Replace(line, "\"" + match.Groups["value"].Value + "\"", "\"" + textBox1.Text + "\"")); }
                                break;
                        }

i have also tried using file.appendalltext but it doesn't work also.

Upvotes: 0

Views: 281

Answers (1)

Dutts
Dutts

Reputation: 6191

I feel that you might be doing this the wrong way, if you are already processing the contents of a file into your application, why not write a method which takes the in-memory values and writes the file out again on save. That way you can handle multiple changes, and won't have to worry about finding a specific point int he file to update.

Obviously there ay be other reason you are doing this, if the contents of the file are too big to hold in memory, for example, but your question doesn't give that much detail.

Upvotes: 4

Related Questions