Michael Low
Michael Low

Reputation: 24506

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.

Upvotes: 1

Views: 256

Answers (3)

EMP
EMP

Reputation: 61971

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.

Upvotes: 3

JaredPar
JaredPar

Reputation: 754545

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) {
    ...
  }
}

Upvotes: 1

Philip Rieck
Philip Rieck

Reputation: 32568

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.

Upvotes: 2

Related Questions