简体   繁体   中英

I can't connect to a SQL Server from a UWA app, but I can with a WinForms app

I built a small Universal Windows app (C#) but I can't connect to my SQL server. The exception reads:

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: TCP Provider, error: 40 - Could not open a connection to SQL Server

The small section of code is simply:

try
{
    using (SqlConnection conn = new SqlConnection(GetConnectionString()))
    {
        await conn.OpenAsync();

        if (conn.State == System.Data.ConnectionState.Open)
        {
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = getAllRunSheetsQuery;

                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    while (await reader.ReadAsync())
                    {
                        var runNumber = reader.GetInt32(0);
                    }
                }
            }
        }
    }
}
catch (Exception eSql)
{
    System.Diagnostics.Debug.WriteLine($"Exception: {eSql.Message} {eSql.InnerException?.Message}");
    throw;
}

The connection string is:

Persist Security Info=False;Application Name=XBAR_Digital_Form;Connect Timeout=2;server=wcsql.wc.com;database=ppd_general_use;User ID=*******;Password=********;

I've also tried a variety of other connections string options to connect to a SQL Server version 2012.

The exception gets thrown at "await conn.OpenAsync()" after the connection timeout. I've confirmed through debugging that the GetConnectionString() method is passing the string correctly.

The weird part is, I can connect just fine with a standard Windows Form app I made with the exact same connection string. I'm using the same general method to connect using System.Data.Sqlclient on both apps. I can connect to the server from any other app (like Excel or Microsoft SQL Server Management Studio)

I found the problem.

I used the Windows Template Studio to create the project. I looked at my Package.appxmanifest and went to Capabilities and found "Private Networks (Client & Server)" was not enabled. After enabling it and rebuilding, the connection worked flawlessly.


can't access to the server on network you have to allow remote connections add TCP and UDP

  • open file explorer post this path "Control Panel\All Control Panel Items\Windows Defender Firewall "
  • on the left side choose advanced settings
  • add new Inbound Rule TCP and port 1433
  • add new Inbound Rule UDP and port 1434

do the same for outbound

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM