How to create an SqlConnection in C# to point to UDL file

可紊 提交于 2019-12-14 02:19:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!