How to get the Name of an application setting in C#?

烂漫一生 提交于 2019-12-05 18:27:17

If you want the name of the setting, then you are looking to get the property name. In the book Metaprogramming in .NET, Kevin Hazzard has a routine that looks something like this:

/// <summary>
/// Gets a property name string from a lambda expression to avoid the need
/// to hard-code the property name in tests.
/// </summary>
public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}

To call it you would do this:

string propertyName = GetPropertyName(() => Myproject.Properties.Settings.Default.mycolor);

I've added a static reflection utility to some of my projects to allow for access to this and other tools.

EDIT

With July 20, 2015 being set as the RTM date for Visual Studio 2015 and .NET 4.6, this seems like a good time for an update.

Happily, all of my above code goes away in C# 6 (.NET 4.6) since there is a new nameof expression that takes care of this very easily now:

string propertyName = nameof(Myproject.Properties.Settings.Default.mycolor);

Some of the new features are described on the MSDN blog.

A little extension method will help you out here:

public static string GetSettingName<TObject, TProperty>(this TObject settings, 
    Expression<Func<TObject, TProperty>> member) 
    where TObject : System.Configuration.ApplicationSettingsBase
{
    var expression = (MemberExpression)member.Body;
    return expression.Member.Name;
}

And it's usage:

var settingName = Properties.Settings.Default.GetSettingName(s => s.mycolor);

Here is my understanding of your requirement:

  • You need to know the setting-name from an object
  • f.e. you want to get "mycolor" from a color like "Red"(presuming that this is the default-value)

You can use the Properties collection and Enumerable.FirstOrDefault:

var colorProperty = Settings.Default.Properties.Cast<System.Configuration.SettingsProperty>()
    .FirstOrDefault(p => color.Equals(p.DefaultValue)); // color f.e "Red"
string nameOfProperty = null;
if (colorProperty != null)
    nameOfProperty = colorProperty.Name;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!