Vous pouvez obtenir votre section de configuration connectionString et modify it, comme ça:
oSection = oConfiguration.GetSection("connectionStrings") as System.Configuration.ConnectionStringsSection;
if (oSection != null)
{
if ((!(oSection.ElementInformation.IsLocked)) && (!(oSection.SectionInformation.IsLocked)))
{
if (protect)
{
if (!(oSection.SectionInformation.IsProtected))
{
blnChanged = true;
// Encrypt the section.
oSection.SectionInformation.ProtectSection
(strProvider);
}
}
else
{
if (oSection.SectionInformation.IsProtected)
{
blnChanged = true;
// Remove encryption.
oSection.SectionInformation.UnprotectSection();
}
}
}
if (blnChanged)
{
// Indicates whether the associated configuration section
// will be saved even if it has not been modified.
oSection.SectionInformation.ForceSave = true;
// Save the current configuration.
oConfiguration.Save();
}
}
Example in VB.NET:
Public Sub ProtectSection()
' Get the current configuration file.
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration
(ConfigurationUserLevel.None)
Dim protectedSection As ConfigurationSection = config.GetSection(m_Section)
' Encrypts when possible
If ((protectedSection IsNot Nothing) _
AndAlso (Not protectedSection.IsReadOnly) _
AndAlso (Not protectedSection.SectionInformation.IsProtected) _
AndAlso (Not protectedSection.SectionInformation.IsLocked) _
AndAlso (protectedSection.SectionInformation.IsDeclared)) Then
' Protect (encrypt)the section.
protectedSection.SectionInformation.ProtectSection(Nothing)
' Save the encrypted section.
protectedSection.SectionInformation.ForceSave = True
config.Save(ConfigurationSaveMode.Full)
End If
End Sub
Vous pouvez utiliser ce code lors de l'installation de votre application (pour vérifier, est le config protected) et vous pouvez vérifier à chaque fois pendant l'exécution de votre application.
MISE À JOUR:
À propos de votre question des commentaires - vous pouvez distribuer votre application avec chaîne de connexion vide, et lors de l'installation, définissez cette propriété (ne pas oublier obfuscation de code dans ce cas) et enregistrer votre fichier de configuration .
Est-ce OK si les personnes autorisées à utiliser l'application voient la chaîne de connexion? Ou devrait-il être gardé secret même d'eux? –
Secret gardé de préférence. – WizardsSleeve
Pourquoi cette question a-t-elle été dépréciée? S'il vous plaît laissez un commentaire lors de la downvotation. Cela semble être une bonne question pour moi. –