开发者

Configuration File For .net(Unable to pass in correct values)

An exert from my config file looks liek this.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
    <add key="loglocal" value="C:\here.txt" />
    <add key="ConnString" value="Data Source=DBNAME;InitialCatalog=CataName;Integrated Security=True"/>
    <add key="UppBound" value="100" />
    <add key="LowBound" value="100" />
    </appSettings>
</configuration

I am attempting to pass in some values into my .net program, and the only one that works is the loglocal which is picking a directory string.

I can pass in my bounds into queries but I cannot pass in the Connection string and open the connection.

I have tried passing in my own set of quotes as well before passing in the long query like:

Dim SQLCONN as new SqlConnection("""" & nameofconfvalue & """")

For reference my entire code looks like this.

Public Class Form1

Dim ConfUpperBound as Integer = Configuration.AppSettings("UppBound")
Dim ConfConnString as String = Configuration.AppSettings("ConnString")

Private Sub Button1_Click(ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Button1.Click
Dim SQLCONN as new SqlConnection("<either from config(fails) or hardcoded(works)>")

//fails on the below line (cannot open Connection)
SQLCONN.Open()

//I can successfully pass in values in query so I know i can connect to conf file
Dim SQLCMD as New SqlCommand("myquery etc etc")    
SQLCMD.ExecuteNonQuery()

SQLCONN.Close()

End Sub
End Class

EDIT: I am able to pass in the string perfectly 开发者_如何转开发when using Visual Studio 2005. But when using VS 2003 and a loiwer .net framework it will not let me, unless I hard code it in.

Could something be enabled/disabled on one of these instances of VS? Or could this just be an error with the older versions of .net? I think I am using 1.1??(will have to check) in 2003.


What version of .net are you using? If you're using 3.5 or above don't put it in the appSettings area, but instead put it in the connectionStrings section.

To read the connection string into your code, use the ConfigurationSettings class like this:

Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("FooBar").ConnectionString)


The ConfigurationSettings.AppSettings method returns a String. Thus you have two options:

1) declare your variable as String:

Dim ConfUpperBound as String = ConfigurationSettings.AppSettings("UppBound")

2) Convert string value to an integer:

Dim ConfUpperBound as Int = Convert.ToInt32(ConfigurationSettings.AppSettings("UppBound"))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜