Click here to Skip to main content
15,921,169 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I using this code for attach mdf ldf files to sql but it Create an exception.
this exception happen also when I do attach manually but when I start sql
as administrator will be disappear.

C#
SqlConnection myConn = new SqlConnection(@"Server=\SQLEXPRESS;Integrated security=True;Initial Catalog=master");

           string query1 = "select name from sys.databases where name='test'";
           SqlDataAdapter da = new SqlDataAdapter(query1 , myConn);
           DataTable dt = new DataTable();
           myConn.Open();
           da.Fill(dt);
           if (dt.Rows.Count == 0)
           {
              string query2 = " CREATE DATABASE [database_name] ON" +
                   "( FILENAME ='test.mdf' )," +
                   "( FILENAME ='test_log.ldf' )" +
                   "FOR ATTACH ;";
              SqlCommand myCommand = new SqlCommand(query2, myConn);
                   myConn.Close();
                   myConn.Open();
                   myCommand.ExecuteNonQuery();
                   MessageBox.Show("DataBase is Created Successfully", "MyProgram",                     MessageBoxButtons.OK, MessageBoxIcon.Information);


error:
..{"Unable to open the physical file \"test.mdf\". Operating system error 5: \"5(failed to retrieve text for this error. Reason: 15105)\"."}
Posted
Updated 22-Apr-14 6:25am
v3
Comments
ZurdoDev 22-Apr-14 9:28am    
Is the file really there and are the permissions sufficient?
mit62 22-Apr-14 12:24pm    
I want Give this permission programatically.
(I changed my code for mdf ldf location)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900