Shirayuki
Shirayuki

Reputation: 1

How to close .mdf file after used by SqlConnection variable

I'm use SqlConnection variable conn to connect to database1.mdf file. Then I use OpenFileDialog and select file database1.mdf to open, but I get the message

This file is in use

from the OpenFileDialog. How do I close that file before reopening it?

This is my code for event Button1_Click. I have rewritten code for simpler. My original code had cn as a global variable so I can't use using keyword for this.

    private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\ADMIN\\Desktop\\CSDL\\DB_Project\\DataBase\\Database1.mdf;Integrated Security=True;Connect Timeout=30;Encrypt=True");

        cn.Open();
        cn.Close();
        
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            // Do something
        }
    }

And this is the message of opendialog when I try to open database1.mdf:

enter image description here

I tried using cn.Dispose(); but it didn't work. I have searched on the internet but there are no solutions for this problem.

I want to know how to close that .mdf file after using by SqlConnection variable. Thanks.

Upvotes: 0

Views: 36

Answers (1)

Shirayuki
Shirayuki

Reputation: 1

I found a way to solve my problem. It's my fault for not explaining clearly. I set openFileDialog1's property to false and changed things from my original intent. However the answer that "I don't open and close .mdf files" is not the answer I wanted for my original purpose. Once again I apologize for not explaining clearly. What I want to do in the //Do something part is execute the command: File.Copy("C:\Users\ADMIN\Desktop\CSDL\DB_Project\DataBase\Database1.mdf", "C: \\Users\ADMIN\Desktop\Database1.mdf"); Although I have found a way to solve the problem, if anyone has a way for me to execute that command, please let me know. Thanks everyone.

Upvotes: 0

Related Questions