Let's say I want to have a file with something like this " Milk 10 Bread 5 Eggs 6 " I want to add a button or something that would allow me to input any numner to change only the number(price) on the one that I choose. How can one do that? Thanks!
Asked
Active
Viewed 106 times
-1
-
You have to rewrite the file. – ProgrammingLlama Mar 30 '21 at 09:52
-
Read the file into `string`, e.g. `string text = File.ReadAllText(@"c:\myFile.txt");` then change `text` into required format; finally, save the `text` back to the file: `File.WriteAllText(@"c:\myFile.txt", text);` – Dmitry Bychenko Mar 30 '21 at 09:52
1 Answers
0
Regex will be the way to go:
For creating regex is: https://regex101.com/ to change 10 to 600 see code below:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"10";
string substitution = @"600";
string input = @"Milk 10 Bread 5 Eggs 6";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
}
}

Connor Stoop
- 1,574
- 1
- 12
- 26
-
You have missed a *little bit* in OP request: *"I want to add a button or something that would allow me to input any numner to change only the number(price) on the one that I choose"*. Though meta say [it's ok](https://meta.stackexchange.com/q/144452/299295). – Sinatr Mar 30 '21 at 09:58
-
Do you need Regex to replace `10` with `600`? The Op is not actually asking how to replace a piece of text with another, but how to write to a file only the part(s) that has/have being changed and not the whole thing. Not impossible, a binary file with fixed length *records* could do it. Kind of an IT Jurassic Park, though. – Jimi Mar 30 '21 at 10:48