Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the resource name from the resource object?

Say I have an exe added into my resources folder. Now how can I get the name (or even the fullpath from which its linked so that I can still have the file name) of the resource as string?

From Properties.Resources.myApp how do I get the string "myApp". ToString() doesnt work. If it is important to embed the file to get the name, I can.

Edit: My question is not specifically to get the name of exe resource. But that one generic approach which gives me the name of the resource! For instance what if my resource is a bitmap image? I need to print "Lily" from Properties.Resources.Lily. How to achieve this? ToString wont work anyways.

like image 928
nawfal Avatar asked Mar 04 '12 14:03

nawfal


People also ask

What is a resource object?

The Resource object is a member of the Resources collection. Using the Resource Object Use Resources (index), where index is the resource index number or resource name, to return a single Resource object. The following example lists the names of all resources in the active project.

What is resource file in C#?

A resource file is a XML file that contains the strings that we want to. Translate into different languages.

What is resource file in Visual Studio?

Visual Studio provides a resource editor that lets you add, delete, and modify resources. At compile time, the resource file is automatically converted to a binary . resources file and embedded in an application assembly or satellite assembly. For more information, see the Resource files in Visual Studio section.


2 Answers

It's quite easy using Linq Expressions:

using System.Linq.Expressions;
//...
static string GetNameOf<T>(Expression<Func<T>> property)
{
  return (property.Body as MemberExpression).Member.Name;
}
// Usage:
var s = GetNameOf(() => Properties.Resources.Lily);

s shoud be Lily

like image 50
Jcl Avatar answered Sep 25 '22 00:09

Jcl


I know this is very old, but the accepted answer is no longer necessarily the best answer. As of C# 6.0 you can just use nameof(...):

string resourceName = nameof(Properties.Resources.MyResourceName);
// resourceName == "MyResourceName"

Much simpler!

like image 20
Ben Avatar answered Sep 25 '22 00:09

Ben