title: How to copy mdf file into a folder with c#
body: <p>I'm using c# and I have a small SQL Server database that I need to copy into a folder <code>C:\databases\</code>, the method name is <code>CreateCopy</code>. </p>
  
  <p>But at File.Copy row appear an error: 
  <code>"The Process cannot Access the File, because it is being use by another Process"</code></p>
  
  <p>I read that File.Copy can be execute only after shut SqlServer down or Detach that database, create a copy and turn SqlServer on again. But how to do it by code?</p>
  
  <p>This is the method that I was trying to use:</p>
  
  <pre><code>public static void CreateCopy()
  {
      try
      {
          DateTime date = DateTime.Now;
          SqlConnection connection = new SqlConnection(MDF_CONNECTION_STRING);
  
          String dbpath = String.Format(@"C:\databases\{0:yyyyMMdd}.mdf", Cash, date);
          File.Copy(@"C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\database.mdf", dbpath);
          String lgpath = String.Format(@"C:\databases\{0:yyyyMMdd}_log.ldf", Cash, date);
          File.Copy(@"C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\database_log.ldf", lgpath);    
      }
      catch(Exception e)
      {
          throw new ApplicationException("Error", e);
      }
  }
  </code></pre>
  
  <p>Thanks in advance! </p>
  
  <p><strong>INFO</strong>
  This is not a duplicate of <a href="https://stackoverflow.com/questions/8681009/copy-sql-server-mdf-and-ldf-files-while-server-is-in-use">here</a> because i don't need to do create a bak file, i need to <strong>archive</strong> this database. I need just to copy these two files (.mdf and .ldf) into a folder. And that answers didn't help me</p>