How to access a database file with non mdf extension - c#

Can we access a database file with non-.MDF extension using C#?
We are creating a setup project. We don't want the user to know the database details which is installed in the installation folder. So, I have tried renaming the database data file and log file with a random name without any extension.
When I have tried accessing the file from c# we are getting an error like:
An attempt to attach an auto-named database to file D:\SQLExpress\DB\abc123tmp failed. A database of the same name exists, or specified file cannot be opened, or it is located at UNC share.
Can anyone help me solve the issue?

Start SSMS, connect to (localDb)\MSSQLLOCALDB and look at the Databases attached ... I guess the File you want to attach is already attached under a different name. Detach that instance first and then your Connection should work. It's not possible to attach the same File using different Database names. The File Extension does not matter.

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.

Can't open databse requested by login, login failed, login failed for user

I have developed c# WPF application, I am using MDF file for database,
my connection string looks like :
Data
Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\appDataBase.mdf;Integrated
Security=True;Connect Timeout=30
here I am replacing |DataDirectory| with user's appdata folder.
the database file is in user's appdata folder, I created a setup which
copies .mdf file to _users appdata folder when I install it in
client's computer, it works perfectly
but when I uninstalls and
reinstall it, I am not able to connect that file, getting the error:
Can't open database
"C:/users/myusername/appdata/roaming/myapplication/database/appDataBase.mdf"
requested by login, login failed, login failed for user..
File is there, but somehow it is used by SQL server and can't
open it. also while starting application every time I am creating
backup of that file, that one also failing with error
System.IO.IOException: The process cannot access the file
'C:\Users\myusername\AppData\Roaming\myapplication\Database\appDataBase.mdf'
because it is being used by another process.
Can anybody give me exact solution, because i have to use localdb only on my client computer , i don't want them let to do any extra configuration for installation of my app, i.am still facing iasue after i changed my code to close db connection on main window closing event.
This type of things happens because one of your object which is using that database is still running in the background so please dispose all the database related instance also dispose and close all the database related object in catch().
Try catch will help you to detect exact line number where you are getting error and also show due to which object you are getting error.
If you want to check why this is happening then open task manager and look out for services there you definitely find service which is holding object for database.

overwrite file in ftp rename command

I have a ftp application. This application uses ftp rename command. If a file already exists in a directory which the file is renamed to, the error message 'the file not avaliable' caught. What can I do in c# to overwrite a file? In IIS there is a setting for this. When I do this, there is no problem.But,can I do this from c#?
What happens when there is a name collision depends on the server, if you cannot configure a known behaviour on each server you connect to you need to deal with it manually.
Either attempt a rename, catch the exception, delete the file then rename again or check for the files existence first (by requesting it size for example) and deleting it if found.

Can't create a database in SQL Server 2012

I have recently installed SQL Server 2012 on my machine. When I try to create a database in SSMS by right clicking on Databases and selecting New Database, it prompts me for various items in order to create the database. After entering the name of the database and clicking OK, I get an exception:
"Create failed for Database 'aaaa'. (Microsoft.SqlServer.Smo)
ADDITIONAL INFORMATION:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
A file activation error occurred. The physical file name 'aaaa.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation. CREATE DATABASE failed. Some file names listed could not be created. Check related errors. (Microsoft SQL Server, Error: 5105)"
It seems the problem is only with the wizard because when I execute Create Database query it successfully creates the database.
I figured it out that when Database is created from wizard, a file path is to be provided in Path column. If it is blank by default then it means there is no path specified in Database settings.
In Object Explorer, right-click a server and click Properties.
In the left panel, click the Database settings page.
In Database default locations, view the current default locations for new data files and new log files. To change a default location, enter a new default path name in the Data or Log field, or click the browse button to find and select a path name.
We can change the file path while creating Database.
The actual database file permissions were set to read_only,please try unchecked the read_only checkbox on the file permissions.
I also had this problem and I can in this link where I've created any string values (DefaultData and DefaultLog) in regedit in this path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer.
In this "string values" you must put the path where your SQL data and log must stay.
As you realized there is a Path column in the grid view for each file (.mdf and .ldf).
This is set to <default>.
At the first usage of the server this default path may not be set, so the full-path of the new database cannot be computed.
Solution:
Based on this article you can set it via the interface of SSMS. You just need to:
right click on your server name (e.g.: (LocalDB)\v11.0),
select Properties,
select Database Settings,
Fill up all 3 entry of Database default locations with valid directory paths. (Defining top 2 paths: Data and Log is enough to create databases.)
This will create the right registry entries for you, without touching regedit.exe.
What path to choose?
Either the location that is proposed along installation:
C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data
Or the location of system databases:
C:\Users\[UserName]\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\v11.0
Or better choices for non-system databases are:
C:\Users\[UserName]\My Documents\Databases
C:\Users\[UserName]\My Documents\SQL Server Management Studio\Databases
Note 1: [UserName] can be "Public" to make it common data (please correct me if this causes multiple copy of the database, but I think it won't).
Note 2: I don't know whether latter is deleted along uninstallation of SSMS.

A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. what does it means?

I Build an ASP.NET project with PL,BL,DAl, BE of Entity Data Model(=.edmx) which I generated from a service Based DB (= .mdf) which is located in my DAL project.
I did copied the connectionString from the BE app.config to the PL web.config
what's wrong? why I get this error:
System.Data.SqlClient.SqlException: An attempt to attach an auto-named
database for file C:\Documents and Settings\user\שולחן העבודה\למידה
אישית\Lev\Lev\App_Data\Midrasha.mdf failed. A database with the same
name exists, or specified file cannot be opened, or it is located on
UNC share.
my code logic is PL->BL->DAL- > try to save the new object to the DB.
the code line which generate the problem is :
public void AddFeedback(Feedback feed)
{
MidrashaEntities _context = new MidrashaEntities();
_context.Feedback.AddObject(feed);
_context.SaveChanges(); <-------throw the exception
}
Feedback is a table in my DAL's SQL which I generate as Object entity.
I had the same error before My Error before in the Connection String so make sure you have the right Connection String
If your on a network and your doc's folder is a share to the AD this will screw you up. Try to move your project to:
C:\MYProject\
and see if that fixes it.

Categories