diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs index da8b65f837..f51723ace2 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs @@ -792,8 +792,19 @@ private static bool IsEndpoint(string dataSource, string prefix) length = foundIndex; } - // check for the instance name - foundIndex = dataSource.LastIndexOf('\\', length - 1, length - 1); + // Safeguard LastIndexOf call to avoid ArgumentOutOfRangeException when length is 0 + if (length > 0) + { + // check for the instance name + foundIndex = dataSource.LastIndexOf('\\', length - 1, length - 1); + } + else + { + foundIndex = -1; + } + + + if (foundIndex > 0) { length = foundIndex; diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.cs index 75fb85b384..d3b906c6b5 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.cs @@ -1082,6 +1082,20 @@ public void ConnectionRetryForNonAzureEndpoints() Assert.Equal(1, (int)field.GetValue(cn)); } + + + [Fact] + public void ConnectionString_WithOnlyComma() + { + // Test Case for https://github.com/dotnet/SqlClient/issues/3110 + // Validates that a single-comma Data Source (e.g., "Data Source=,") no longer causes ArgumentOutOfRangeException + // Instead, it should throw a SqlException indicating a connection failure + + SqlConnection cn = new SqlConnection("Data Source=,;Initial Catalog=master;Integrated Security=True"); + Assert.Throws(() => { cn.Open(); }); + + } + [Theory] [InlineData("myserver.database.windows.net")] [InlineData("myserver.database.cloudapi.de")]