自定义将数据源变量嵌入连接字符串中

时间:2019-02-14 06:50:38

标签: c# asp.net oledbconnection

我如何自定义调用连接字符串的数据源,现有的连接字符串存储在web.config文件中。我正在使用Oledb连接到已上传到服务器的Excel工作表。

我的连接字符串在web.config文件中。之前,我对整个字符串进行了硬编码,包括web.config文件中的数据源位置。

//this one works
<add name="testexcel1" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\usethis\WebApplication1\Uploaded Files\weekly output target.xlsx;Extended Properties='Excel 12.0 Xml;HDR=No;IMEX=1;MAXSCANROWS=0'"/>

//I would like to specify the data source parameter in my code behind file.
   <add name="testexcel" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=No'"/>

//this is what I am trying to do, but it just does not work, the string gets concatenated wrongly.
string fileLocation = Server.MapPath("~/Uploaded Files/" + filename);
builder.Provider = ConfigurationManager.ConnectionStrings["testexcel1"].ConnectionString;
        builder.DataSource = accept_filelocation;

//This is finally working
string connectionStringProvider =
ConfigurationManager.ConnectionStrings["testexcel1"].ConnectionString;

        string dataSource = accept_filelocation;

        string connectionString = String.Format(connectionStringProvider, dataSource);



        OleDbConnection oledbConn = new OleDbConnection(connectionString);

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么您想从配置中读取连接字符串格式(包括{0})并将其应用于给定的数据源:

string connectionStringFormat = 
    ConfigurationManager.ConnectionStrings["testexcel1"].ConnectionString;

string dataSource = Server.MapPath("~/Uploaded Files/" + filename);

string connectionString = String.Format(connectionStringFormat, dataSource);
var builder = new OleDbConnectionStringBuilder(connectionString);