简体   繁体   中英

How can I replace a unknown string in a file?

Currently I'm writing a library to make reading and writing INI files simple, I have got the reader working and writing when the key and value doesn't exist but I cannot update the value easily, I have tried various methods to replace the string however none are practical and the program requires the old value

Here is an example I have tried from here: Regular Expression to replace unknown value in text file - c# and asp.net

Regex rgx = new Regex(@"SQL-SERVER-VERSION="".*?""");
string result = rgx.Replace(input, replacement);

But every time I modify that code to replace the value it ends up replacing the key instead thus resulting in an error when the app tries to read the file next time.

Here is the code I am using currently:

private string wholedata;
private void UpdateKey(string key, string path, string newval)
{
    try
    {
        using (StreamReader s = new StreamReader(File.Open(path, FileMode.Open)))
        {
            wholedata = s.ReadToEnd();
            Regex rgx = new Regex(key + ".*?");
            string result = rgx.Replace(wholedata, newval);
            MessageBox.Show(result);
        }
        using (StreamWriter s = new StreamWriter(File.Open(path, FileMode.OpenOrCreate)))
        {
            s.Write(wholedata);
        }
     }
     catch (Exception e)
     {
     }
}

Why rewriting what the system already know how to do? Take a look at this project : An INI file handling class using C# . You should also be aware that Xml has taken a great place in the .Net framework. It's not uncommon to use either the configuration framework or a simple settings object that you serialize/deserialize. I don't know you requirement, but it can enlight us to describe a bit why you want to use ini files.

That said, you are writing the old value (wholedata), not the new value (result). This may be be the root cause.

When you call Regex.Replace (so do string.Replace ), it actually generate a new string, and does not change the string passed in parameters.

Change the regex to

Regex rgx = new Regex(@"(?<=SQL-SERVER-VERSION="").*?(?="")");

This will match the .*? on the proviso that the prefix and suffix exist ( (?<=) and (?=) groupings)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM