问题
I have a .udl (Universal data link) file in my project. Now I want to create an SQL Connection that should point to this particular file. SqlConnection object expects a connection string, how can we build an SqlConnection using .UDL file?
回答1:
From MSDN site:
It is possible to supply connection information for an OleDbConnection in a Universal Data Link (UDL) file; however you should avoid doing so. UDL files are not encrypted, and expose connection string information in clear text. Because a UDL file is an external file-based resource to your application, it cannot be secured using the .NET Framework. UDL files are not supported for SqlClient.
Have a look here:
http://social.msdn.microsoft.com/Forums/en-US/sqlnetfx/thread/0bb40f32-86f4-4b6f-a2e0-bc2bdcf07b63
回答2:
An alternative way is to convert OleDBConnection to SQLConnection.
private static string CONNECTION_NAME = "\\conection.udl";
private static SqlConnection CreateSqlConnection(OleDbConnection udlInfo)
{
try
{
string CONNECTION_STRING = $"Database={udlInfo.Database};Server={udlInfo.DataSource};Integrated Security=True;connect timeout = 30";
var connection = new SqlConnection(CONNECTION_STRING);
connection.Open();
return connection;
} catch
{
Console.WriteLine($"{CONNECTION_NAME} Not found");
return null;
}
}
public static SqlConnection GetSqlConnection()
{
var udlInfo = new OleDbConnection($"File Name={Application.StartupPath}{CONNECTION_NAME}");
return CreateSqlConnection(udlInfo);
}
来源:https://stackoverflow.com/questions/16234370/how-to-create-an-sqlconnection-in-c-sharp-to-point-to-udl-file