Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ADO.NET: Can't connect to mdf database file

I'm writing an application that uses a SQL Server 2005 database. In the connection string I'm specifying the mdf file like this:

connstr = @"Data Source=.\SQLEXPRESS; AttachDbFilename=" + fileLocation + "; Integrated Security=True; User Instance=True";

When I execute the code:

public static void forceConnection()
{
    try
    {
        conn = new SqlConnection(connstr);
        conn.Open();
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        if(conn != null)
            conn.Close();
    }
}

I receive an exception:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

This code works on XP but not in Vista. I tried to run Visual Studio in admin mode and moved the mdf file to "user data" folders but the error persists.

Any help?

like image 306
Nabo Avatar asked Dec 25 '10 15:12

Nabo


2 Answers

Can you connect to the sql server db in your command prompt? I would make sure you can actually connect first.

Try open the cmd prompt and type sqlcmd -S .\SQLEXPRESS -d your_dbase

like image 148
locoboy Avatar answered Oct 04 '22 22:10

locoboy


If I have mssql-connect problems with my dotnet-sourcecode I try to connect to the database with a different program. I use queryexpress that is also written in dotnet. If this program works then I know that the problem is with my program code else the problem is with connection string, proxy, network, sqlserver or user permissions.

like image 32
k3b Avatar answered Oct 04 '22 22:10

k3b