开发者

Detecting what platform code is running on in C#?

I have C# code I want to use in both a WinForms app and ASP.NET website. The database connection string differs for each though, so I want to be able to find out which platform it's running on and set the connection string appropriately. Is there an easy/recommended way to do this ?

This should compile on both WinForms and ASP.NET开发者_运维问答, so nothing that needs either a System.Windows or System.Web reference please.


The framework already handles this for you. Use System.Configuration.ConfigurationManager.AppSettings or ConfigurationManager.ConnectionStrings to read your connection strings and they will be read from App.config in WinForms and from Web.config in ASP.NET. You can put different values in the two config files.

As for the more general question - you could check System.Web.HttpContext.Current and if it's not null you're definitely running inside ASP.NET. If it's null you're probably not in ASP.NET, but may just not be inside a request. You could also try checking some of the properties on System.Web.HttpRuntime.

Edit: If you don't want to add a reference to System.Web.dll you could call the above via Reflection: first call Type.GetType("System.Web.HttpContex") and if that returns null then you're definitely not in ASP.NET. If it returns a value you can then proceed to get the Current static property on it.


The recommended way is to store the connection string in a configuration file - either App.Config or Web.Config, and use the ConfigurationManager to read from that. See Storing and Retrieving Connection Strings from MSDN.


Having the database code detecting the platform it's running on seems like the wrong solution. No matter what you choose it seems like there would be a way to beat it.

Instead I would have the entry point of my application express it's platform declaratively.

enum Platform {
  AspNet,
  WinForms
}

public class DataConnection {
  public DataConnection(Platform platform) {
    ...
  }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜