title: How to encrypt and decrypt custom configuration files (XML files) in C#
body: <p>I am new to the forums.</p>
  
  <p>I've just started working on C# and webservices for the past 3 months and I've got a great web service rearing to go. Unfortunately, there is a custom "configuration" file (really an XML file) that we use to store our connection strings.</p>
  
  <p>We don't want to use the web.config connectionstring section because the class and the associated xml file that was written in house, will be used by other projects not just web services. The problem is I need to encrypt the username and passwords of the "configuration" XML file and decrypt it in my C# code.</p>
  
  <p>Suffice to say the XML file has the following structure ...</p>
  
  <pre><code>&lt;?xml version='1.0'?&gt;
  &lt;!--
  TEST ENVIRONMENT
  --&gt;
  &lt;thesystem&gt;
     &lt;connectionString string="Data Source=( DESCRIPTION = ( ADDRESS_LIST = ( ADDRESS = ( PROTOCOL = TCP )( HOST = {0} )( PORT = {1} ) ) )( CONNECT_DATA = ( SERVER = DEDICATED )( SERVICE_NAME = {2} ) ) ); User Id= {3}; Password = {4};"/&gt;
     &lt;oracleDetails&gt;
       &lt;site name="thesite"&gt;
         &lt;schema dbname="thedb"    dbHost="99.99.99.99" dbPort="9999" dbServiceName="SYSTEMSITE" dbUsername="xxx" dbPassword="yyy"/&gt;
       &lt;/site&gt;
     &lt;/oracleDetails&gt;
  &lt;/thesystem&gt;
  </code></pre>
  
  <p>I've looked on the web and managed to "cheat" around a way to encrypt the file using aspnet_regiis.exe</p>
  
  <p>ie:</p>
  
  <blockquote>
    <p>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pef oracleDetails . -prov DataProtectionConfigurationProvider</p>
    
    <p>Encrypting configuration section...
    Succeeded!</p>
  </blockquote>
  
  <p>I got this to work by renaming the  tag to  and renaming the xml file to web.config. I tricked ASP.net to think I am encrypting a web configuration file.</p>
  
  <p>The problem now is how do I decrypt it in C#?</p>
  
  <p>I've tried using the following ...</p>
  
  <pre><code>Configuration _myConfig = ConfigurationManager.OpenExeConfiguration("OURSYSTEM.config");
  </code></pre>
  
  <p>where <code>OURSYSTEM.config</code> is the XML file above.</p>
  
  <p>It program throws an error saying it cannot locate the file. And besides, the OpenExeConfiguration is more for Win apps with the app.config file.</p>