110,566
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace ConnStrEncry
{
public class Utils
{
public static void ProtectConnectionString()
{
ToggleConnectionStringProtection(System.Windows.Forms.Application.ExecutablePath, true);
}
public static void UnprotectConnectionString()
{
ToggleConnectionStringProtection(System.Windows.Forms.Application.ExecutablePath, false);
}
private static void ToggleConnectionStringProtection(string exePath, bool protect)
{
// Define the Dpapi provider name.
string strProvider = "DataProtectionConfigurationProvider";
// string strProvider = "RSAProtectedConfigurationProvider";
Configuration configuration = null;
ConnectionStringsSection section = null;
// Open the configuration file and retrieve
// the connectionStrings section.
// For Web!
// oConfiguration = System.Web.Configuration.
// WebConfigurationManager.OpenWebConfiguration("~");
// For Windows!
// Takes the executable file name without the config extension.
configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(exePath);
if (configuration != null)
{
bool blnChanged = false;
section = configuration.GetSection("connectionStrings") as ConnectionStringsSection;
if (section != null)
{
if ((!(section.ElementInformation.IsLocked)) && (!(section.SectionInformation.IsLocked)))
{
if (protect)
{
if (!(section.SectionInformation.IsProtected))
{
blnChanged = true;
// Encrypt the section.
section.SectionInformation.ProtectSection(strProvider);
}
}
else
{
if (section.SectionInformation.IsProtected)
{
blnChanged = true;
// Remove encryption.
section.SectionInformation.UnprotectSection();
}
}
}
if (blnChanged)
{
// Indicates whether the associated configuration section
// will be saved even if it has not been modified.
section.SectionInformation.ForceSave = true;
// Save the current configuration.
configuration.Save();
}
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConnStrEncry
{
class Program
{
static void Main(string[] args)
{
Utils.ProtectConnectionString();
string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString;
Console.WriteLine(connstr);
Console.Read();
}
}
}