简体   繁体   中英

C# Replace string in different file types

I am supposed to build an .NET6 app that should retrieve passwords for few accounts using an API and update the different types of configuration files (XML, JSON, INI, shell scripts, etc) with the retrieved password.

I am not sure how can I match the row in the file that I must update, considering that the password might be hashed in those files.

For example, one of the files is a XML with the following fields:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Saved on Thu Sep 23 17:02:13 CEST 2021</comment>
<entry key="db.password">!password</entry>
<entry key="db.username">USERNAME</entry>
</properties>

In this case I am supposed to replace the !password with the value I got from the API.

Another example is a shell script that might contain the password in a hashed format:

# Password
export DB_PASSWORD_ENC=LtWHTYsL5w5mJFH4snLrSA==

Is there a generic way to find the entry I need to update? I was thinking using a regex and string.Replace(oldPassword, newPassword);

Here is a regex to find the db.password tag and the value (no matter what the password value is)

<entry key="db.password">[\S\s]*?</entry>\s*

You could then use a string replace to replace it with

<entry key="db.password">your-new-password</entry>

You could also optimize this regex to match the value of the password (,password). hover i'm afraid I can't help with that as my regex knowledge is limited.

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