简体   繁体   English

如何替换文件中的未知字符串?

[英]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 目前,我正在编写一个库来简化读取和写入INI文件的过程,当键和值不存在时让阅读器可以工作和编写,但是我无法轻松地更新值,我尝试了各种方法来替换字符串但是都不可行,程序需要旧值

Here is an example I have tried from here: Regular Expression to replace unknown value in text file - c# and asp.net 这是我在这里尝试过的一个示例: 正则表达式替换文本文件中的未知值-c#和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# . 看一下这个项目: 使用C#的INI文件处理类 You should also be aware that Xml has taken a great place in the .Net framework. 您还应该知道Xml在.Net框架中占据了重要位置。 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. 我不知道您的要求,但这可以启发我们描述您为什么要使用ini文件。

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. 调用Regex.Replacestring.Replace也是string.Replace ),它实际上会生成一个新字符串,并且不会更改传入参数的字符串。

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) 前提是存在前缀和后缀( (?<=)(?=)分组)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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