string dbPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dbPath = Path.Combine(dbPath, "Database1.mdf");
cn = new SqlConnection (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory| " dbPath ";Integrated Security=True");
GetAllRecords();
When I run this code, it displays this error
System.NotSupportedException: 'The given path's format is not supported.'
I want to connect the database located in current user's document folder. How to fix this?
CodePudding user response:
The AttachDbFilename
attribute of the connection string has to actually contain the path to the file. Yours obviously does not. At run time, |DataDirectory|
gets replaced with the path of the data directory, which will likely be the folder from which your executable was run. If your data file is in your documents folder then it's obviously not under the program folder, so why are you using |DataDirectory|
at all? Get rid of that and use the path of the data file.
The point of |DataDirectory|
is that you can put your data file in your program folder and hard-code the path, even though you won't actually know the path of that folder until run time. If you're not storing your data file in the data directory then don't use |DataDirectory|
in the connection string. That is most useful when you have a source data file in your project folder that is automatically copied to your output folder when you build. |DataDirectory|
will then work while debugging and after release, no matter where the application is.
CodePudding user response:
I think it just needs to be new SqlConnection ($"...AttachDbFilename={dbPath}");
without the DataDirectory
.