Connect to SQL Server database with appconfig, C#

alan smith 1 Reputation point
2021-03-08T19:42:15.343+00:00

I am trying to connect to a SQL Server database with appconfig but however I am getting the following error:

"An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll".

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.Named Pipes Provider, error: 40 - could not open connection to sql server.

Here is my code:

SqlConnection conexion = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conectar"].ConnectionString);

the error is happening on the line: conexion.Open();

Appconfig:

<connectionStrings>
    <add name ="conectar" connectionString="server=servername;Integrated security=yes; Database=Base01"/>
</connectionStrings>

the error is happening on the line: conexion.Open();

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,743 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,266 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Sam of Simple Samples 5,516 Reputation points
    2021-03-08T21:48:54.773+00:00

    Are the SQL Server services running? You can use SQL Server Configuration Manager to check.

    What happens when you access the database using SQL Server Manager Studio (SSMS)? Can you see the tables using it?

    Can you connect to the server using SQL Server Object Explorer in Visual Studio? If so then right-click on the database and select Properties. Look at the connection string there.

    0 comments No comments

  2. Karen Payne MVP 35,036 Reputation points
    2021-03-09T03:16:33.893+00:00

    Try the following with your server and catalog then if it works place the connection string into your app.config. Also see ConnectionStrings.

    using System;
    using System.Data.SqlClient;
    
    public class DataOperations
    {
        public static bool TestConnection()
        {
    
            var connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=NorthWindAzure;Integrated Security=True";
    
            using (var cn = new SqlConnection { ConnectionString = connectionString })
            {
                try
                {
                    cn.Open();
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return false;
    
                }
    
            }
    
        }
    }
    

    If you need to check if the server is running and available. A robust version is found here.

    using System;
    using System.Data;
    using System.Data.Sql;
    using System.Linq;
    using System.ServiceProcess;
    using System.Threading.Tasks;
    
    
    public class Utilities
    {
        /// <summary> 
        /// Determine if SQL-Server is available 
        /// </summary> 
        /// <returns></returns> 
        public async Task<bool> SqlServerIsAvailable()
        {
            bool success = false;
    
            try
            {
                await Task.Run(() =>
                {
                    SqlDataSourceEnumerator sqlDataSourceEnumeratorInstance = SqlDataSourceEnumerator.Instance;
                    DataTable dt = sqlDataSourceEnumeratorInstance.GetDataSources();
                    if (dt != null)
                    {
                        success = true;
                    }
                });
            }
            catch (Exception ex)
            {
                // ignored
            }
    
            return success;
        }
        /// <summary> 
        /// Determine if a specific SQL-Server is available 
        /// </summary> 
        /// <param name="pServerName"></param> 
        /// <returns></returns> 
        public async Task<bool> SqlServerIsAvailable(string pServerName)
        {
    
            bool success = false;
    
            try
            {
                await Task.Run(() =>
                {
                    SqlDataSourceEnumerator sqlDataSourceEnumeratorInstance = SqlDataSourceEnumerator.Instance;
                    DataTable dt = sqlDataSourceEnumeratorInstance.GetDataSources();
                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            var row = dt.AsEnumerable().FirstOrDefault(r => r.Field<string>("ServerName") == pServerName.ToUpper());
                            success = row != null;
                        }
                        else
                        {
                            success = false;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
    
            return success;
        }
        /// <summary>
        /// Determine if a specific service is running e.g.
        /// SQL-Server: MSSQLServer
        /// MSSQLSERVER
        /// SQL Server Agent: SQLServerAgent
        /// SQL Server Analysis Services: MSSQLServerOLAPService
        /// SQL Server Browser: SQLBrowser
        /// </summary>
        /// <param name="serviceName">Service name to find</param>
        /// <returns>True if found, false if not</returns>
        public static bool ISWindowsServiceRunning(string serviceName)
        {
            var isRunning = false;
            var services = ServiceController.GetServices().
                Where(sc => sc.ServiceName.Contains("SQL")).ToList();
    
            foreach (var service in services)
            {
                if (service.ServiceName == serviceName)
                {
                    if (service.Status == ServiceControllerStatus.Running)
                    {
                        isRunning = true;
                    }
    
                }
            }
    
            return isRunning;
        }
    }
    
    0 comments No comments

  3. Duane Arnold 3,216 Reputation points
    2021-03-09T07:11:22.777+00:00

    Is MS SQL Server on a machine on the network, you have not configured MS SQL Server to accept remote connections and you have not fingered the firewall running on the machine to open MSSQL Server port?

    0 comments No comments