Unable to open the physical file Operating system error 32 - c#

Well this i did the below to get the error, don't have a clue why the database connection fails.
Create a new ASP.NET Website
Add a new *.mdf database to App_Data
Add some tables to it using Server Explorer in Visual Studio
Right click DataBase and Copy Connection string. Insert it into WebConfig File like below
<connectionStrings>
<add name="DB" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\inetpub\wwwroot\gs\App_Data\db.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Add some code to get the data from
selectStatement = "select * from users";
SqlDataAdapter da = new SqlDataAdapter(selectStatement,
ConfigurationManager.ConnectionStrings["DB"].ConnectionString);
DataTable dtUsers = new DataTable();
da.Fill(dtUsers);
GridView1.DataSource = dtUsers.DefaultView;
GridView1.DataBind();
and zoot you get the error

I have a sneaky suspicion it has to do with permissions. Give full control to your "Authenticated Users".
In case you are wondering how to do this --- I am on Windows 7 and the steps go like this:
Right-click on the MDF file and click properties.
Select the "Security" tab and select your "Authenticated Users" (or
something that looks right).
Click "Edit" and select the "Allow" check-box for "Full Control".
OK all the way out.
HTH

The top result from Google seems to address your question:
Just in case if anybody is still looking for solution to this error, this works for me:
1) Open the VStudio project for which
you need to connect to a SQL database
2)Separately, Go to
Start->Run->Services.msc
3) Look for
SQL Server (SQLEXPRESS) service and
Stop it
4) Start it again
5) Try
connecting your database now.
Looks like the reason it works has
something to do with User Instance
discussion that is going on in this
thread.

I was struggling with this error to and I found that the error was in the database instance that was online so I took it offline from SQLserver management studio,I've shared the steps followed and the solution HERE

In my case, I had the database in instance MSSQLSERVER while trying to attach it to SQLEXPRESS. Dropping from the first instance freed the file.

About error: Operating system error 32, Open error ...
First off all, give permission to mdf file. In my case NETWORK SERVICE account have FULL ACCESS on data.mdf.
Well, my workspace:
SSMS have attached data.mdf
In same time in VS2010 I have open solution with same database file: data.mdf, but can not make successfully connection.
Solution: in CONNECTION PROPERTIES on USER INSTANCE change TRUE to FALSE and refresh connection inside VS on this database.
Finaly, no more opening error and you have access on same database file in same time from SSMS and VS2010.
Connection string example:
DataSource=.\SQLEXPRESS;AttachDbFilename=D:\Contracts\App_Data\data.mdf;Integrated Security=True;User Instance=False
Regards
Dražen-ZG

Related

How do I create a generic file path to a local database in a C# Application?

I have a simple data entry Windows Form with a datagridview display that links to a local database. When I run the program and try to add data on another computer, I get this message:
Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.
An attempt to attach an auto-named database for file C:\Users\roberto.yepez\Documents\Visual Studio\2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
The file path is to the path on the computer where I coded the program.
Here is my code:
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True".ToString());
I am a self-taught coder, please help! :)
I believe you're running into a problem because your local sql server to which your code is trying to attach the StudentInfo1.mdf (whose path is in the connection string) already contains a database called StudentInfo1 - it decided to try and create a database of this name based on the name of the mdf file. I'm guessing that you can pick your own name by specifying Initial Catalog in your connection string but this would mean there are two databases with possibly the same set of tables and a potential for confusion
Per the comment I posted I would instead advocate that you use SQL Server Management Studio to permanently attach your db (you make have already done this) and then adjust your connection string so that it refers to the permanently attached db. This reduces the chances that your next question will be "my code says it's updating my db but I cannot see any changes!?"
Please move this connection string
"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True"
to app.config file. When you deploy to production, change the paths in that app.config, according to the production machine settings.
You can even apply transformations on the app.config to deploy in various machines/scenarios.

First chance exception of 'System.Data.EntityException'. The underlying provider failed on Open

I've been given a site that was created by someone else and I'm now trying to test it. I can compile the system without any problems but when I try to log in to the website, I get the error:
"EntityException occured. A first chance exception of type 'System.Data.EntityException' occured in System.Data.Entity.dll. Additional info: The underlying provider failed on Open."
Furthermore, if I dig deeper, I see an InnerException of Cannot open database \"MyDB\" requested by the login. The login failed. Login failed for user 'name\\owner'.
I've read similar problems on the web and it seems like its a problem with database connections? I've tried multiple 'solutions' that include messing around with the connectionString but nothing works.
What I think the system wants to do is connect to a .mdf located in a separate project's App_Data. Anyway, here's the connectionString code that I received originally:
add name="NameServiceContext"
connectionString="Server=tcp:qiu5vg5yhv.database.windows.net,1433;Database=MyDB;User ID=MYID;Password=MYPASS;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
providerName="System.Data.SqlClient"
Quick question, what is the tcp:...... stuff? I'm assuming it was generated somehow, but how?
I've tried 'fixing' the problem and ended up with something like this:
add name="NameServiceContext"
connectionString="data source=./SQLEXPRESS;AttachDbFilename=C:\Users\owner\Documents\MyERP\App_Data\MyDB.mdf;Integrated Security=True;Connect Timeout=30;"
providerName="System.Data.SqlClient"
Both methods give the same errors and I'm out of ideas. How would I go about fixing this?
Also, when I connect to a db via tools>connect to database > MS SQL db file, I get an option between 2 data sources, ./SQLEXPRESS and (LocalDB)\v11.0. Do I have to include both of them? If so, how?
The original connection string refers to a Microsoft Azure instance. A typical connection string to Azure looks like:
Server=tcp:[serverName].database.windows.net;Database=myDataBase;User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;Encrypt=True;
Your server name is qiu5vg5yhv.database.windows.net. Most likely your credentials are incorrect.
It is as Andrew said, you don't seem to have access to the actual database. Simply download either "SQL Server Management Studio" or "SQL Server Management Studio Express" (depend on which version of database you are using) and try to connect.
If you connect successfully, check if you can query the database of your project.
If you connect unsuccessfully, contact your system admin to arrange access.
If you want to understand more about connectionstring or create one, use the following site for template: http://www.connectionstrings.com/sql-server/
You can get the necessary database details by viewing the Properties of your database via "SQL Server Management Studio" (right click and select Properties --> View Connection Properties)
I met the same question. The key step is here.
I used vs 2013 update 4.
When you configured your SQL in azure, it generated a connect string.

Unable to connect to SQL Server locally

I am getting the following exception when I am trying to connect to a web service
System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file DatabaseName.mdb failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
The connection string I am using is:
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|WS_Assignment.mdb;uid=Admin;pwd="
providerName="System.Data.OleDb"
I am trying to access SQL Server on local system.
I have gone through a lot of articles and followed all the different methods. But I got no solution.
Can anyone help me out?
Before Question was EDITED:
are you deploying on a web server , instead of your localhost. If thats the case you need to publish the sql script in Server DB as servers dont allow attachDB file in your deployment and if thats the case then your problem is solved.
After Update
you can always try with fullpath and yes you need OLEDB call not sql make sure thats not the case with your .cs code
Correction in your question:
i am trying to access SQL server On local system
:
i dont see how you can do that with .mdb file; even if thats not the case make sure sql services are running properly in your system go to->start button->program files->microsoft sql server yourversion-> configuration manager-> check running services.
In your Solution Explorer, click on "Show All Files". then go to your App_Data folder and delete WS_assignment.mdb and then run your application.
Also, your provider is wrong
providerName="System.Data.SqlClient" is the right one.
Secondly, your database name should end in .mdf or .sdf for SQL Server.
So, your connection string will become:
<connectionStrings>
<add name="ConnectionStringName"
connectionString="Data Source=|DataDirectory|WS_Assignment.sdf"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Check this.
http://msdn.microsoft.com/en-IN/library/5ybdbtte%28v=vs.71%29.aspx
using Access requires System.Data.OleDb library

Windows Form Application and SQL Server

UPDATE 2
I fixed the error by adding System.Configuration to the reference file. I had already added it to my class with using System.Configuration;
I found the answer here: The name 'ConfigurationManager' does not exist in the current context
Any further issues will be addressed in a new question.
Original(ish) Post
I have Microsoft SQL Server Management Studio. In the studio I created a database called Logbook that exists locally on my computer.
I have also created a user interface using a Windows forms application in VS C# Express. I would like to connect it to my logbook database in order to update, select, delete, and insert entries into the database through the UI.
However, I cannot figure out how connect the two. I have played around with the "Add new data source" wizard to no avail. I also cannot find anything helpful in the MSDN or other tutorials online.
UPDATE
I created a new database and project to work with until I figure out how to properly do this so I don't accidently break anything in my project.
The Schema is:
Student(sid: int, fname: char(10), lname: char(10), age:int, major:char(10))
Course(cid:int, desc:char(50), dept:char(10))
Enrolled(sid:int, cid:int, quarter:char(10), grade:char(10))
Here is the connection string generated by the "Add Data Source" wizard
<add name="boathouseLogConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\boathouseLog.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
I have successfully gotten my database into the project. However, when I try running a stored procedure I get this error Argument Exception was unhandled. Format of the initialization string does not conform to specification starting at index 0.
The error occurs on line 2.
DataTable dt = new DataTable();
SqlConnection sqlConn = new SqlConnection(selectedConnectionString);
SqlCommand myCommand = new SqlCommand("proc_getMember", sqlConn);
myCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(myCommand);
the selectedConnectionString variable is set to boathouseLogConnectionString
Initial Hints
If you want to see some examples for windows forms connecting to a database i can recommend the forms over data video series. Video 2 is about how to connect to a database.
In the app.config file you can put your connection data
<connectionStrings>
<add name="OrderManager.My.MySettings.OMSConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\OMS.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
To be able to help you better i need more details. If you connect in management studio you can take a look at your connections properties. What are the values here and so on.
Update
There is another question with a similar problem. May be you are running user instances. Please add more details:
add information about your connection string (i am assuming your are using file attached connnections with a local data file)
where do you click on your database? Are you clicking on the mdf file or are you using management studio or visual studio
There is two major ways, you can use Entity Framework or ADO.NET foundation.
For simple tasks you can use ado.net features. at first you have to create SqlConnection Object and pass your ConnectionString to the constructor. Second you have to use SqlCommand Object and set your desired Command Text for the command. and at last you have to Execute the Command. there are several ways for execution :
ExecuteNonQuery For Updates, Deletes and Inserts commands
ExuecuteReader For Select commands, this methods returns a SqlDataReader which you can get your result from it.

Database Error while launching application

I deployed C# application and created installer. Installer gets created successfully but when tried to launch the application it throws up following error:
An attempt to attach an auto-named database for file CampusPointe.mdf
failed. A database with the same name exists, or specified file cannot
be opened, or it is located on UNC share.
connection string in app.config is as follows:
<connectionStrings>
<add name="App_Key_Management.Properties.Settings.VendorKeyConnectionString1"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Program Files\Vendor Key Management\VendorKey.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Any help would be appreciated.
Regards,
Sri
Sri,
First of all, you need to ensure a couple of things:
1. You have installed SQL Server
2. You need to deal with the creation or replacement of the file you created. I think this is your issue ... If the .mdf file exists then you need to either update the existing file or drop and replace it (USE [database] GO DROP TABLE... GO CRATE TABLE ... GO). You will also need to consider step 4 below.
3. If you are accessing a a file located in a database you need a fully formed name. You also need to add the database user to the connection string in ASP.NET Web.Config or App.config (depending on the app). I looks like you have started this ...
4. Make sure the user account that you are using in the connection string has the necessary privileges on the database side. If this is a full fledged database in SQL SERVER then the user account will need update, delete, create privileges. If you are replacing or creating databases on the fly then the user will need CREATE DATABASE or DROP / CREATE privileges.
I think to best answer your question we would need more information on the architecture of the application. My guess is that your code creates the database fine the first time and then when you try to run it the second time it fails because the database is already there. If this is the case you also need to address your code (with IF statements or SWITCH CASE ... your call) to handle situations where the table (1) does not exist and needs to be created; (2) exists and needs to be updated; and / or (3) exists and needs to be replaced. The correct answer again depends on your code and what you are trying to do.

Categories