Background:
I am developing a little budgeting program with an SQL backend.
The database is stored in a Sharepoint, and the files are ALL on my PC.
Program consists of a main form with a 3-tab tabcontrol, each has a control I have built. each assigns data to charts/datagridviews in code. No element is linked in designer to the SQL.
This is a local instance of the SQL, not a server.
Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\(username +
sharepoint local
folder)\Winforms_Learning\budgetApp_V0.1\Database1.mdf";Integrated
Security=True
In settings for the project, connection string is:
Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated
Security=True
Issue - when loading the form, it gives the below error:
system.data.sqlclient.sqlexception (0x80131904): an attempt to attach an auto-named database for file c:\program files\microsoft visual studio\2022\community\common7\ide\database1.mdf failed. a database with the same name exists, or specified file cannot be opened, or it is located on unc share
All configs point to the correct location. the connection strings all point to the correct location.
However, I can't find any reference whatsoever that points to that filepath.
That filepath does not contain any database files at all. I've never used it.
I have moved the solution to a folder local on my machine (i.e. - not Sharepoint), fixed all the Connection strings and issue persists.
I've found a similar issue with another user here:
An attempt to attach an auto-named database for file ....database1.mdf failed
This solution doesn't apply in my case.
Any help is extremely welcome
p.s. - well aware of there being no security and possibility for code injection etc. not implementing that until I've got the majority of the code done.
Currently installing VS22 on another machine to test there on a fresh install.
You might hit a very common issue with how Visual Studio and LocalDB handle the AttachDbFilename
connection string, especially when using |DataDirectory|
. The error message suggests that DataDirectory
is being resolved to:
C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\
This typically happens when you're debugging the app in Visual Studio and the AppDomain.CurrentDomain.SetData("DataDirectory", ...)
isn't explicitly set.
Manually set the DataDirectory
in your code (e.g., in Program.cs before Application.Run(...)):
AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(Application.StartupPath, "App_Data"));
Then, make sure your database is inside a folder called App_Data
(create it if needed), and use this connection string in App.config like you used in your code.
|DataDirectory|
, switch to an explicit path programmatically:string dbPath = @"C:\Users\YourName\Path\To\Database1.mdf";
string connectionString = $@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={dbPath};Integrated Security=True";
** Be careful with this during deployment or moving the project.