开发者

How to make the connection string of an Windows form application in C#.net,Computer independent?

As I transfer my Windows form application in C#.net from one computer to another, I have 开发者_如何学JAVAto change the connection string every time as the location of the Database file has changed.

How can I can I prevent this,so that I don't have to change the connection string again and again?


If the service you need to connect is always running on the local machine, you might use the localhost as the server name...

By the way localhost is mapped to the ip 127.0.0.1 in the hosts file.


Have your DB file in the same location of your application exe and then you can use

Application.StartupPath()

to get the path.

*I am assuming that this is a Windows Forms Application.


How has the location of the database changed? Is it not in a central location that all computers/users can access?

If not, you could store the connection information in settings and create a form that allows you to update those as needed. The form could be launched as part of the installer or on first run of the application.

A little more information about what you're doing would be helpful in presenting a real solution.


It's tricky to tell without an example of the type of connection string you're using (or which database you're accessing) but can't you use a relative path and assume that the database is somewhere relative to your app?

If you set your connection sting up like this...

<connectionStrings>
    <add name="ConsoleApplication1.Properties.Settings.Database1ConnectionString"
        connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"
        providerName="System.Data.SqlClient" />
</connectionStrings>

... then |DataDirectory| will by default resolve to the application's folder. You can, however, change DataDirectory by calling the AppDomain.SetData method. See the following for how to change it...

http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/805bfd29-d864-4400-b353-bea13167f046

I've shown how you'd set the connection string in config, but the same holds true if you're setting it in code. If you are building a connection string in code, then may I suggest you look at using a connection string builder...

http://msdn.microsoft.com/en-us/library/ms254947.aspx

I am, of course, assuming a file path in your connection string, but if it's a database then won't localhost also work?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜