Skip to content

Instantly share code, notes, and snippets.

@ANovokmet
Created August 21, 2023 15:42
Show Gist options
  • Save ANovokmet/417a9b8c29be4b39e8984b4d4a7dd28d to your computer and use it in GitHub Desktop.
Save ANovokmet/417a9b8c29be4b39e8984b4d4a7dd28d to your computer and use it in GitHub Desktop.
Migrate .NET Framework Web.config file to .NET Core appsettings.json
const fs = require('fs');
const path = require('path');
migrateConfigs(fs.readdirSync(`C:/Solution1/Project1/Config`), `C:/Solution1/Project1/Config`);
function migrateConfigs(files, folder) {
files = files.filter(f => f.endsWith('.config') && f.startsWith('App.'));
for(const fileName of files) {
console.log(fileName)
const appConfig = {
ConnectionStrings: {}
};
let fileContent = fs.readFileSync(path.join(folder, fileName)).toString();
const appSettingsContent = fileContent.match(/<appSettings>([\s\w\W]*)<\/appSettings>/gm);
if(appSettingsContent) {
const asMatch = appSettingsContent[0].matchAll(/<add .*key="(.*)".*value="(.*?)".*\/>.*$/gm);
for(const m of asMatch) {
const [_, key, value] = m;
appConfig[key] = value;
}
}
const connStringsContent = fileContent.match(/<connectionStrings>([\s\w\W]*)<\/connectionStrings>/gm);
if(connStringsContent) {
const csMatch = connStringsContent[0].matchAll(/<add [\w\W\s]*name="(.*)"[\w\W\s]*connectionString="(.*)"[\w\W\s]*?\/>/gm);
for(const m of csMatch) {
const [_, key, value] = m;
appConfig.ConnectionStrings[key] = value;
}
}
// Web.Configuration1.config -> appsettings.Configuration1.json
if(fileName !== 'App.config') {
const [_, name] = fileName.match(/App\.(.*)\.config/);
fs.writeFileSync(path.join(folder, `appsettings.${name}.json`), JSON.stringify(appConfig, null, ' '));
} else {
fs.writeFileSync(path.join(folder, `appsettings.json`), JSON.stringify(appConfig, null, ' '));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment