简体   繁体   中英

Create Backup of attached database file

I have Database file .mdf which is installed with setup where application installed.

All database operation Insert,Update delete works fine but only problem arise in back up.

Now i want to make back up of attached mdf file to application installed path when i click on backup button.

Following is my connection string.

<add name="MyConstring" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Database=Database;Integrated Security=True;User Instance=True;Connect Timeout=30" providerName="System.Data.SqlClient" />

Code which create back up.

        string serverName = "";
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
        builder.ConnectionString = ConfigurationManager.ConnectionStrings["MyConString"].ToString();
        string server = builder.DataSource;
        string attachDBFilename = builder.AttachDBFilename;
        string DatabaseName = "[" + builder.InitialCatalog + "]";

        string SQLBackUp = @"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + @"d:\Data\" + "Aa.bak" + @"'";
        string svr = "Server=" + server + ";Database=master;Integrated Security=True";
        SqlConnection cnBk = new SqlConnection(svr);
        SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);

            cnBk.Open();
            cmdBkUp.ExecuteNonQuery();

Above code give following error only if i use database file attached.

But is gives error

"Database does not exist"

Your database service engine account must have access to that physical file. As error suggest it's a operating system error. So You need to give proper permission on that folder or file.

See following link.

http://dbamohsin.wordpress.com/2009/06/03/attaching-database-unable-to-open-physical-file-access-is-denied/

Write click on folder and goto security and give proper permission to the data folder so that your SQL server user can access that folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM