[C#] Get Project Resource by Name

2016. 6. 24. 10:28Coders

프로젝트 내부 리소스로부터 이름을 가지고 값을 가져오는 메서드 입니다. 일반적으로는 리소스야 내가 붙인 것이니 이러한 코딩을 하진 않겠지만, 동적으로, 또는 분기를 태우면 코드가 길어지기 때문에 다음과 같은 메서드를 만들어 놓으면, 분기를 태우지 않고 리소스를 가져올 수 있습니다.

Linq를 사용하는데요, where 절을 적절히 변형 시키면 원하는 값을 가져 올 수 있습니다. 여러개의 데이터도 가져올 수 있겠지요.

이 코드는 사용하다가, 웹 프로젝트라 리소스를 프로젝트에 넣지 않고 그냥 Static한 웹 페이지의 리소스로 변경하려고 하다가 기존 작성했던 게 아까워서 블로그에 올립니다.

코드 입니다.

/// <summary>
/// Get Resource From My Project
/// </summary>
/// <typeparam name="T">Resource Type</typeparam>
/// <param name="resourceName">Resource Name</param>
/// <returns>Resource</returns>
internal static T GetResource<T>(string resourceName)
{
	ResourceSet rscSet = Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);

	if (rscSet != null)
	{
		var sourceCodeListButOne =
			from entry in rscSet.Cast<DictionaryEntry>()
			where entry.Value.GetType() == typeof(T) && entry.Key.ToString().Equals(resourceName, StringComparison.CurrentCultureIgnoreCase)
			select entry.Value;

		if (sourceCodeListButOne.Count() > 0)
			return (T)sourceCodeListButOne.First();
	}

	return default(T);
}

'Coders' 카테고리의 다른 글

[MSSQL] CREATE OR REPLACE PROCEDURE  (0) 2016.08.17
[C#] Get Available Fixed Drive  (0) 2016.06.14
[CSS] 맑은고딕 폰트 Weight 문제  (0) 2016.06.02